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

Middleware

Before, after, and instead: building a pipeline that others can trust.

The point: give each link the rest of the chain as a function. Then it can work before, work after, stop, retry or catch, and the order is a list.

Shape

An onion

In and out again

The first in the list is the first on the way in and the last on the way out. Django's documentation calls it an onion.

A pipeline, part by part

The whole contract is two function types.

from dataclasses import dataclass, fieldfrom typing import Callable@dataclassclass Request:    path: str    headers: dict = field(default_factory=dict)    user: str = ""@dataclassclass Response:    status: int    body: str = ""Endpoint = Callable[[Request], Response]Middleware = Callable[[Request, Endpoint], Response]

Lines 5 to 9

The request carries a place for what earlier links find out. Name it as a field: a dictionary that everyone writes into hides who depends on whom.

1 of 2

Failure walk

Four bugs that pass review

BugWhat users seeDefence
Neither answers nor calls nextThe request hangs until a timeoutMake the function return a response: the type checker asks for it
Calls next twiceCharged twiceThe once guard
Forgets await before nextErrors escape the catch, the after part runs too earlyA lint rule for floating promises, a test with a failing endpoint
Keeps request data in the middleware objectOne user sees the data of anotherPer request data belongs in the request

How does one link tell a later one who the user is?

BreaksA field in the middleware object
How
self.user = ... in the shared object.
Limit
Two requests at the same time overwrite each other.
Choose when
Never.
WorksA dictionary on the request
How
request.ctx["user"].
Limit
Typing errors, hidden dependencies, wrong order found at run time.
Choose when
Generic frameworks.
StrongA typed field or a new request type
How
AuthenticatedRequest with a user that cannot be missing.
Limit
More types. Middleware becomes less generic.
Choose when
Your own services: the compiler then checks the order.