Extensions#
An extension is a separate package that adds a key to the top-level types it applies to. Model decodes the key’s value and passes it to the extension’s own templates, but never reads the value itself. A package that rate limits routes, for example, can let each route state how often a client may call it:
type: route
display: Route Stop
desc: Looks up a stop
method: GET
path: /route/owners/{owner}/stops/{stop}/{priority}
request: StopLookup
success_response: StopLookup
error_response: ErrorResponse
rate_limit:
requests: 60
seconds: 60
So far extensions apply only to routes, and only the Go output renders them.
Enabling an extension#
An installed extension does nothing until a model enables it in model.toml,
by its entry point name:
[tool.model]
extensions = ["rate_limit"]
A key that neither the type nor an enabled extension claims is still loaded, but the build warns about it. The key is probably misspelt, or belongs to an extension the model does not enable.
In Go#
The generated package declares a RouteExtensions struct, with one field for
each enabled extension. Its type is mdl.ExtMiddleware of the extension’s
config type, and RegisterAllEndpoints takes it before the other middleware:
type RouteExtensions struct {
RateLimit mdl.ExtMiddleware[ratelimit.Limit]
}
func RegisterAllEndpoints(router *mdl.Router, exts RouteExtensions, middleware ...mdl.Middleware)
Each route that sets an extension’s key is wrapped in that field’s middleware, outside the other middleware. The middleware is given the route’s value for the key, already in the extension’s own Go type, so it has nothing to look up. A route that does not set the key is not passed to it.
catalog.RegisterAllEndpoints(router, catalog.RouteExtensions{RateLimit: ratelimit.Enforce})
The middleware comes from the extension’s Go package, and works with any model:
func Enforce(route mdl.Route, limit Limit, next http.Handler) http.Handler {
clients := newCounters(limit.Window)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if clients.Add(r.RemoteAddr) > limit.Requests {
w.WriteHeader(http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
RegisterAllEndpoints panics when a route sets a key whose field is nil.
That way a route is never served without the middleware that its YAML asks
for. A model that enables no extension has no RouteExtensions, and its
RegisterAllEndpoints has no exts parameter.
Writing an extension#
An extension is a class with four class attributes, the
model.extensions.Extension protocol:
from typing import ClassVar
from msgspec import Struct
class RateLimitOptions(Struct, frozen=True, forbid_unknown_fields=True):
requests: int
seconds: int
class RateLimitExtension:
key: ClassVar[str] = "rate_limit"
applies_to: ClassVar[frozenset[str]] = frozenset({"route"})
config: ClassVar[type] = RateLimitOptions
go_route_ext: ClassVar[str | None] = "ratelimit_ext.route_go"
Attribute |
Meaning |
|---|---|
|
The top-level YAML key it claims. It cannot be a key the type already has, and no two enabled extensions can claim the same key. |
|
The |
|
The msgspec type the key’s value decodes to. Its values must be hashable, as a frozen struct’s are. |
|
The module path of a compiled template that renders the extension in Go, or |
The template exports two macros. go_type renders the Go config type, and
go_value takes a decoded value and renders it as a Go expression of that
type. Each adds the imports it needs with $depend_on:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ratelimit_ext import RateLimitOptions
---
$macro go_type():
$depend_on("example.com/ratelimit")
ratelimit.Limit
$endmacro
$macro go_value(options: RateLimitOptions):
$depend_on("example.com/ratelimit")
$depend_on("time")
ratelimit.Limit{Requests: ${options.requests}, Window: ${options.seconds} * time.Second}
$endmacro
The Go package, example.com/ratelimit here, declares the config type and the
mdl.ExtMiddleware for it. The field in RouteExtensions is the key in
PascalCase.
Model imports this module only when it renders, so it never compiles the
template. Ship the compiled module (route_go.py) in your package.
Install the class as an entry point in the model.extensions group. The entry
point’s name is the one that model.toml lists:
[project.entry-points."model.extensions"]
rate_limit = "ratelimit_ext:RateLimitExtension"