From a2551d83d7fafe9e0598fc1dfd81c895340e505a Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Wed, 18 Nov 2026 20:07:39 +0100 Subject: [PATCH] docs(pact,party,surf): compile README Go examples via src= (quick-261118-qsd) --- modules/pact/README.md | 42 +++++--------- modules/pact/example_test.go | 93 ++++++++++++++++++++++++++++++- modules/party/README.md | 56 ++++++++++++------- modules/party/example_test.go | 72 ++++++++++++++++++++++++ modules/party/export_docs_test.go | 11 ++++ modules/surf/README.md | 69 +++++++++++------------ 6 files changed, 257 insertions(+), 86 deletions(-) create mode 100644 modules/party/export_docs_test.go diff --git a/modules/pact/README.md b/modules/pact/README.md index f5529f05..0941760d 100644 --- a/modules/pact/README.md +++ b/modules/pact/README.md @@ -46,25 +46,11 @@ Use cases: ## Usage -A plugin declares its capabilities by implementing the interfaces and asserting them at compile time: +A plugin declares its capabilities by implementing the interfaces, and asserts them at compile time with lines such as `var _ pact.HasRoutes = (*BlogPlugin)(nil)`: -```go -package blog - -import ( - "net/http" - - "git.golem15.com/golem15/summercms/modules/pact" -) - -var ( - _ pact.HasRoutes = (*Plugin)(nil) - _ pact.HasPermissions = (*Plugin)(nil) -) - -type Plugin struct{} - -func (p *Plugin) Routes(r pact.Router) error { +```go src=modules/pact/example_test.go#BlogPlugin.Routes +// Routes declares the plugin's JSON API behind the auth middleware. +func (p *BlogPlugin) Routes(r pact.Router) error { r.Group("/api/blog", []string{"auth"}, func(r pact.Router) { r.Get("/posts", listPosts) r.Get("/posts/{id}", showPost) @@ -72,26 +58,26 @@ func (p *Plugin) Routes(r pact.Router) error { }) return nil } +``` -func (p *Plugin) Permissions() []pact.Permission { +```go src=modules/pact/example_test.go#BlogPlugin.Permissions +// Permissions declares the backend permission that guards the post screens. +func (p *BlogPlugin) Permissions() []pact.Permission { return []pact.Permission{ {Code: "acme.blog.access_posts", Tab: "Blog", Label: "Manage posts"}, } } - -func listPosts(w http.ResponseWriter, r *http.Request) {} -func showPost(w http.ResponseWriter, r *http.Request) {} ``` -A plugin schedules one of its registered commands by implementing `pact.HasSchedule`: +A plugin schedules its registered console commands by implementing `pact.HasSchedule`: -```go -var _ pact.HasSchedule = (*Plugin)(nil) - -func (p *Plugin) Schedule() []pact.ScheduledCommand { +```go src=modules/pact/example_test.go#BlogPlugin.Schedule +// Schedule runs three of the plugin's registered console commands. +func (p *BlogPlugin) Schedule() []pact.ScheduledCommand { return []pact.ScheduledCommand{ {Command: "blog:prune-drafts", Cadence: pact.Daily()}, - {Command: "blog:ping", Args: []string{"--quiet"}, Cadence: pact.Every(15 * time.Minute)}, + {Command: "blog:send-digest", Cadence: pact.DailyAt(7, 30)}, + {Command: "blog:sync-feed", Args: []string{"--quiet"}, Cadence: pact.Every(15 * time.Minute)}, } } ``` diff --git a/modules/pact/example_test.go b/modules/pact/example_test.go index f1091af0..7eceafa4 100644 --- a/modules/pact/example_test.go +++ b/modules/pact/example_test.go @@ -2,15 +2,44 @@ package pact_test import ( "fmt" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" "time" "git.golem15.com/golem15/summercms/modules/pact" ) -// BlogPlugin is the acme.blog plugin; only its schedule is shown here. +// BlogPlugin is the acme.blog plugin: routes, permissions and a schedule. type BlogPlugin struct{} -var _ pact.HasSchedule = (*BlogPlugin)(nil) +var ( + _ pact.HasRoutes = (*BlogPlugin)(nil) + _ pact.HasPermissions = (*BlogPlugin)(nil) + _ pact.HasSchedule = (*BlogPlugin)(nil) +) + +// Routes declares the plugin's JSON API behind the auth middleware. +func (p *BlogPlugin) Routes(r pact.Router) error { + r.Group("/api/blog", []string{"auth"}, func(r pact.Router) { + r.Get("/posts", listPosts) + r.Get("/posts/{id}", showPost) + r.Where("id", "[0-9]+") + }) + return nil +} + +// Permissions declares the backend permission that guards the post screens. +func (p *BlogPlugin) Permissions() []pact.Permission { + return []pact.Permission{ + {Code: "acme.blog.access_posts", Tab: "Blog", Label: "Manage posts"}, + } +} + +func listPosts(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "posts") } +func showPost(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "post "+r.PathValue("id")) } // Schedule runs three of the plugin's registered console commands. func (p *BlogPlugin) Schedule() []pact.ScheduledCommand { @@ -35,3 +64,63 @@ func ExampleHasSchedule() { // blog:send-digest []: daily at 07:30 // blog:sync-feed [--quiet]: every 15m0s } + +// routeRecorder is a pact.Router that records each route and constraint and +// keeps the handlers, standing in for surf's router. +type routeRecorder struct { + prefix string + middleware []string + lines *[]string + handlers map[string]http.HandlerFunc +} + +func (r routeRecorder) group(prefix string, mw []string, fn func(pact.Router)) { + fn(routeRecorder{r.prefix + prefix, append(slices.Clone(r.middleware), mw...), r.lines, r.handlers}) +} +func (r routeRecorder) add(method, path string, h http.HandlerFunc, mw []string) { + route := method + " " + r.prefix + path + *r.lines = append(*r.lines, route+" "+strings.Join(append(slices.Clone(r.middleware), mw...), ",")) + r.handlers[route] = h +} +func (r routeRecorder) Group(p string, mw []string, fn func(pact.Router)) { r.group(p, mw, fn) } +func (r routeRecorder) GroupRaw(p string, mw []string, fn func(pact.Router)) { r.group(p, mw, fn) } +func (r routeRecorder) Get(p string, h http.HandlerFunc, mw ...string) { r.add("GET", p, h, mw) } +func (r routeRecorder) Post(p string, h http.HandlerFunc, mw ...string) { r.add("POST", p, h, mw) } +func (r routeRecorder) Put(p string, h http.HandlerFunc, mw ...string) { r.add("PUT", p, h, mw) } +func (r routeRecorder) Patch(p string, h http.HandlerFunc, mw ...string) { r.add("PATCH", p, h, mw) } +func (r routeRecorder) Delete(p string, h http.HandlerFunc, mw ...string) { r.add("DELETE", p, h, mw) } +func (r routeRecorder) Where(param, pattern string) { + *r.lines = append(*r.lines, "where "+param+" "+pattern) +} +func (r routeRecorder) WhereIn(param string, values ...string) { + *r.lines = append(*r.lines, "where "+param+" in "+strings.Join(values, ",")) +} + +// TestDocsDeclarations checks the routes and permissions the README shows +// and serves both handlers. +func TestDocsDeclarations(t *testing.T) { + p := &BlogPlugin{} + var lines []string + rec := routeRecorder{lines: &lines, handlers: map[string]http.HandlerFunc{}} + if err := p.Routes(rec); err != nil { + t.Fatal(err) + } + want := []string{"GET /api/blog/posts auth", "GET /api/blog/posts/{id} auth", "where id [0-9]+"} + if !slices.Equal(lines, want) { + t.Fatalf("routes = %q, want %q", lines, want) + } + mux := http.NewServeMux() + for route, h := range rec.handlers { + mux.HandleFunc(route, h) + } + for path, body := range map[string]string{"/api/blog/posts": "posts", "/api/blog/posts/7": "post 7"} { + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) + if w.Body.String() != body { + t.Fatalf("GET %s = %q, want %q", path, w.Body, body) + } + } + if perms := p.Permissions(); len(perms) != 1 || perms[0].Code != "acme.blog.access_posts" { + t.Fatalf("Permissions() = %+v", perms) + } +} diff --git a/modules/party/README.md b/modules/party/README.md index 58f1deca..37f092e3 100644 --- a/modules/party/README.md +++ b/modules/party/README.md @@ -32,25 +32,43 @@ Use cases: ## Usage -A plugin registers itself when its package is imported: +A plugin registers itself when its package is imported. The plugin type implements `party.Plugin`: -```go -package blog +```go src=modules/party/example_plugin_test.go#BlogPlugin +// BlogPlugin is the acme.blog plugin: the Go form of a WinterCMS Plugin.php. +// A real plugin package also registers it from init with +// party.Register(&BlogPlugin{}). +type BlogPlugin struct{} +``` -import ( - "git.golem15.com/golem15/summercms/modules/backpack" - "git.golem15.com/golem15/summercms/modules/party" -) +```go src=modules/party/example_plugin_test.go#BlogPlugin.ID +// ID is the plugin identifier in vendor.plugin form. +func (p *BlogPlugin) ID() string { return "acme.blog" } +``` -type Plugin struct{} +```go src=modules/party/example_plugin_test.go#BlogPlugin.Requires +// Requires lists the plugins that must register and boot first ($require). +func (p *BlogPlugin) Requires() []string { return []string{"acme.user"} } +``` -func (p *Plugin) ID() string { return "acme.blog" } -func (p *Plugin) Requires() []string { return []string{"acme.user"} } -func (p *Plugin) Register(app *backpack.App) error { return nil } -func (p *Plugin) Boot(app *backpack.App) error { return nil } +```go src=modules/party/example_plugin_test.go#BlogPlugin.Register +// Register runs before any plugin boots: publish services here. +func (p *BlogPlugin) Register(app *backpack.App) error { return nil } +``` -func init() { - party.Register(&Plugin{}) +```go src=modules/party/example_plugin_test.go#BlogPlugin.Boot +// Boot runs after every plugin registered: listen to events and look up +// services other plugins published. +func (p *BlogPlugin) Boot(app *backpack.App) error { return nil } +``` + +and the package's `init` function registers it: + +```go src=modules/party/example_test.go#registerBlog +// registerBlog is the blog plugin package's init function: a real package +// names it init, so importing the package registers the plugin. +func registerBlog() { + party.Register(&BlogPlugin{}) } ``` @@ -60,10 +78,10 @@ Each application gets its own plugin instances: `party.Activate` gives every app The application publishes its build-time metadata and activates the plugins it lists, in dependency order (`summer build` generates both lists): -```go -cfg, err := compass.Load("config") +```go src=modules/party/example_test.go#activate +cfg, err := compass.Load(dir) if err != nil { - return err + return nil, nil, err } app := backpack.New(cfg) info := []party.Info{ @@ -71,11 +89,11 @@ info := []party.Info{ {ID: "acme.blog", Version: "v0.2.5", Source: party.SourceModule}, } if err := party.Describe(app, info, "v0.6.0"); err != nil { - return err + return nil, nil, err } plugins, err := party.Activate(app, []string{"acme.user", "acme.blog"}) if err != nil { - return err + return nil, nil, err } ``` diff --git a/modules/party/example_test.go b/modules/party/example_test.go index 3eafb6c3..e3002d6e 100644 --- a/modules/party/example_test.go +++ b/modules/party/example_test.go @@ -2,7 +2,11 @@ package party_test import ( "fmt" + "slices" + "testing" + "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/compass" "git.golem15.com/golem15/summercms/modules/party" ) @@ -11,3 +15,71 @@ func ExamplePlugin() { fmt.Println(p.ID()) // Output: acme.blog } + +// registerBlog is the blog plugin package's init function: a real package +// names it init, so importing the package registers the plugin. +func registerBlog() { + party.Register(&BlogPlugin{}) +} + +// userPlugin is the acme.user plugin BlogPlugin requires. +type userPlugin struct{} + +func (*userPlugin) ID() string { return "acme.user" } +func (*userPlugin) Requires() []string { return nil } +func (*userPlugin) Register(*backpack.App) error { return nil } +func (*userPlugin) Boot(*backpack.App) error { return nil } + +// startApp is the part of an application's generated main that loads the +// configuration in dir and activates the plugins. +func startApp(dir string) (*backpack.App, []party.Plugin, error) { + // docs:start activate + cfg, err := compass.Load(dir) + if err != nil { + return nil, nil, err + } + app := backpack.New(cfg) + info := []party.Info{ + {ID: "acme.user", Source: party.SourceLocal}, + {ID: "acme.blog", Version: "v0.2.5", Source: party.SourceModule}, + } + if err := party.Describe(app, info, "v0.6.0"); err != nil { + return nil, nil, err + } + plugins, err := party.Activate(app, []string{"acme.user", "acme.blog"}) + if err != nil { + return nil, nil, err + } + // docs:end activate + return app, plugins, nil +} + +// TestDocsActivate registers both plugins, starts an application on an +// empty config directory and checks the activation order, the published +// metadata and the plugin methods the README shows. +func TestDocsActivate(t *testing.T) { + party.DocsRegistry(t) + registerBlog() + party.Register(&userPlugin{}) + + app, plugins, err := startApp(t.TempDir()) + if err != nil { + t.Fatal(err) + } + var ids []string + for _, p := range plugins { + ids = append(ids, p.ID()) + } + if want := []string{"acme.user", "acme.blog"}; !slices.Equal(ids, want) { + t.Fatalf("activated %v, want %v", ids, want) + } + installed, ok := app.Lookup[party.Installed]() + if !ok || installed.Framework != "v0.6.0" { + t.Fatalf("Installed = %+v, %v", installed, ok) + } + + p := plugins[1] + if !slices.Equal(p.Requires(), []string{"acme.user"}) || p.Register(app) != nil || p.Boot(app) != nil { + t.Fatalf("BlogPlugin methods: %v", p.Requires()) + } +} diff --git a/modules/party/export_docs_test.go b/modules/party/export_docs_test.go new file mode 100644 index 00000000..896151ee --- /dev/null +++ b/modules/party/export_docs_test.go @@ -0,0 +1,11 @@ +package party + +import "testing" + +// DocsRegistry swaps the process-wide plugin registry for an empty one for +// the length of the test, for the docs examples in example_test.go that +// register plugins. +func DocsRegistry(t *testing.T) { + t.Helper() + withRegistry(t) +} diff --git a/modules/surf/README.md b/modules/surf/README.md index 80615d8f..a3195cc1 100644 --- a/modules/surf/README.md +++ b/modules/surf/README.md @@ -48,58 +48,56 @@ Use cases: A plugin declares routes, middleware and a rate-limit bucket; the runtime assembles them: -```go -package blog - -import ( - "net/http" - "time" - - "git.golem15.com/golem15/summercms/modules/backpack" - "git.golem15.com/golem15/summercms/modules/pact" - "git.golem15.com/golem15/summercms/modules/surf" - "git.golem15.com/golem15/summercms/modules/wire" -) - -type Plugin struct{} - -func (Plugin) ID() string { return "acme.blog" } -func (Plugin) Requires() []string { return nil } -func (Plugin) Register(*backpack.App) error { return nil } -func (Plugin) Boot(*backpack.App) error { return nil } - -func (Plugin) Middlewares() map[string]pact.Middleware { - return map[string]pact.Middleware{ - "blog.no-store": func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Cache-Control", "no-store") - next.ServeHTTP(w, r) - }) - }, +```go src=modules/surf/example_test.go#BlogPlugin.Middlewares +// Middlewares registers the plugin's named middleware: here, a JWT guard +// that answers 401 when the request has no valid token. +func (p *BlogPlugin) Middlewares() map[string]pact.Middleware { + guards := bouncer.NewRegistry() + guard := bouncer.NewJWTGuard(secret, users{}, bouncer.NewMemoryBlacklist()) + if err := guards.Register(p.ID(), "acme.auth", guard); err != nil { + panic(err) } + auth, err := guards.Middleware("acme.auth") + if err != nil { + panic(err) + } + return map[string]pact.Middleware{"acme.auth": auth} } +``` -func (Plugin) Buckets() map[string]surf.Bucket { +```go src=modules/surf/example_test.go#BlogPlugin.Buckets +// Buckets declares a named rate limit, used as throttle:blog.comments. +func (p *BlogPlugin) Buckets() map[string]surf.Bucket { return map[string]surf.Bucket{ "blog.comments": { - Max: 5, + Max: 1, Decay: time.Minute, - Key: func(r *http.Request) string { return "comments|" + surf.ClientIP(r, nil) }, + Key: func(r *http.Request) string { return "comments|" + surf.ClientIP(r, p.trusted) }, }, } } +``` -func (Plugin) Routes(r pact.Router) error { +```go src=modules/surf/example_test.go#BlogPlugin.Routes +// Routes is the Go form of the plugin's routes.php. +func (p *BlogPlugin) Routes(r pact.Router) error { r.Group("/api/blog", surf.Use("throttle:60,1"), func(g pact.Router) { g.Get("/posts/{id}", showPost) g.Where("id", `[0-9]+`) - g.Get("/posts/{status}/list", listPosts, "blog.no-store") + g.Get("/posts/{status}/list", listPosts) g.WhereIn("status", "draft", "published") - g.Post("/posts/{id}/comments", addComment, "throttle:blog.comments", "body.limit:65536") + + // An auth group: every route inside needs a signed-in user. + g.Group("", surf.Use("acme.auth"), func(auth pact.Router) { + auth.Get("/me", showMe) + auth.Post("/posts/{id}/comments", addComment, "throttle:blog.comments", "body.limit:65536") + }) }) return nil } +``` +```go src=modules/surf/example_test.go#showPost func showPost(w http.ResponseWriter, r *http.Request) { id, ok := surf.IntParam(r, "id") if !ok { @@ -108,9 +106,6 @@ func showPost(w http.ResponseWriter, r *http.Request) { } wire.WriteJSON(w, http.StatusOK, map[string]any{"id": id}) } - -func listPosts(w http.ResponseWriter, r *http.Request) { wire.WriteJSON(w, http.StatusOK, []string{}) } -func addComment(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) } ``` Routes ported from a `routes.php` sometimes overlap: `GET /shelves/items/{id}` with `id` numeric and `GET /shelves/{shelfId}/follow` with `shelfId` numeric both match `/shelves/items/follow` as patterns, so ServeMux alone would refuse to register them. surf registers such routes as an overlap family and tries them in registration order, checking literal segments and `Where` constraints, so declare them in the same order as the PHP file. A request no member matches gets the bare 404. Overlapping routes must use literal segments and single-segment `{name}` wildcards; two routes of one method with the same shape, a `{name...}` wildcard in a family, or a more general route that would take a member's requests still fail at boot. `surf.Router.Routes` and `route:list` keep listing every route on its own.