Chain of responsibility
medium 45 minA 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
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
| Bug | What users see | Defence |
|---|---|---|
| Neither answers nor calls next | The request hangs until a timeout | Make the function return a response: the type checker asks for it |
| Calls next twice | Charged twice | The once guard |
| Forgets await before next | Errors escape the catch, the after part runs too early | A lint rule for floating promises, a test with a failing endpoint |
| Keeps request data in the middleware object | One user sees the data of another | Per 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
AuthenticatedRequestwith a user that cannot be missing.- Limit
- More types. Middleware becomes less generic.
- Choose when
- Your own services: the compiler then checks the order.