docs(lighthouse,postcard,signpost): compile README Go examples via src= (quick-261118-qsd)

This commit is contained in:
Jakub Zych
2026-11-18 20:13:14 +01:00
parent a2551d83d7
commit 1e56d750ef
7 changed files with 482 additions and 150 deletions

View File

@@ -2,8 +2,12 @@ package lighthouse_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"slices"
"strconv"
"strings"
"testing"
"time"
@@ -11,6 +15,9 @@ import (
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/lighthouse"
_ "git.golem15.com/golem15/summercms/modules/lighthouse/centrifugo"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/surf"
"gorm.io/gorm"
)
@@ -194,3 +201,145 @@ func TestDocsBroadcast(t *testing.T) {
t.Fatalf("summary = %+v %s", pubs[1], pubs[1].Payload)
}
}
// RoomsPlugin is the acme.rooms plugin: room:{id} channels for members.
type RoomsPlugin struct {
realtime *lighthouse.Service
}
// lookupAcmeUser stands in for the application's own user model.
func lookupAcmeUser(ctx context.Context, id uint) (lighthouse.User, bool, error) {
if id != 42 {
return lighthouse.User{}, false, nil
}
name := "Ada"
return lighthouse.User{ID: id, Name: &name}, true, nil
}
// isRoomMember stands in for the application's own membership query.
func isRoomMember(ctx context.Context, userID uint, roomID int64) bool {
return userID == 42 && roomID == 7
}
// Boot builds the realtime service, installs the user lookup and registers
// the room authorizer.
func (p *RoomsPlugin) Boot(app *backpack.App) error {
svc, err := lighthouse.From(app)
if err != nil {
return err
}
p.realtime = svc
svc.SetUserLookup(func(ctx context.Context, id uint) (lighthouse.User, bool, error) {
return lookupAcmeUser(ctx, id) // the application's own user model
})
// Allow room:{id} to members only; re-checked on every subscribe.
return svc.Registry().Register("room", lighthouse.AuthorizerFunc(
func(ctx context.Context, userID uint, channel string) lighthouse.Result {
if isRoomMember(ctx, userID, lighthouse.ChannelID(channel)) {
return lighthouse.Allowed(nil)
}
return lighthouse.Denied("not a room member")
}))
}
// Routes mounts the driver's routes once.
func (p *RoomsPlugin) Routes(r pact.Router) error {
return lighthouse.Mount(r, p.realtime.Driver(), lighthouse.Surfaces{
UserAuth: surf.Use("jwt.auth"),
ServerToServer: surf.Use(),
Middleware: surf.Use("throttle:acme-realtime"),
})
}
// routeRecorder is a pact.Router that records each route with its
// middleware, standing in for surf's router.
type routeRecorder struct {
prefix string
middleware []string
lines *[]string
}
func (r routeRecorder) group(prefix string, mw []string, raw bool, fn func(pact.Router)) {
if raw {
mw = append([]string{"raw"}, mw...)
}
fn(routeRecorder{strings.TrimSuffix(r.prefix+prefix, "/"), append(slices.Clone(r.middleware), mw...), r.lines})
}
func (r routeRecorder) add(method, path string, mw []string) {
*r.lines = append(*r.lines, method+" "+r.prefix+path+" "+strings.Join(append(slices.Clone(r.middleware), mw...), ","))
}
func (r routeRecorder) Group(p string, mw []string, fn func(pact.Router)) { r.group(p, mw, false, fn) }
func (r routeRecorder) GroupRaw(p string, mw []string, fn func(pact.Router)) {
r.group(p, mw, true, fn)
}
func (r routeRecorder) Get(p string, _ http.HandlerFunc, mw ...string) { r.add("GET", p, mw) }
func (r routeRecorder) Post(p string, _ http.HandlerFunc, mw ...string) { r.add("POST", p, mw) }
func (r routeRecorder) Put(p string, _ http.HandlerFunc, mw ...string) { r.add("PUT", p, mw) }
func (r routeRecorder) Patch(p string, _ http.HandlerFunc, mw ...string) { r.add("PATCH", p, mw) }
func (r routeRecorder) Delete(p string, _ http.HandlerFunc, mw ...string) { r.add("DELETE", p, mw) }
func (routeRecorder) Where(string, string) {}
func (routeRecorder) WhereIn(string, ...string) {}
// TestDocsRoomsPlugin boots the README's plugin on the centrifugo driver,
// checks its user lookup and room authorizer, and mounts its routes.
func TestDocsRoomsPlugin(t *testing.T) {
app, err := newApp(map[string]any{"realtime.driver": "centrifugo", "realtime.centrifugo.token_secret": "docs-secret"})
if err != nil {
t.Fatal(err)
}
p := &RoomsPlugin{}
if err := p.Boot(app); err != nil {
t.Fatal(err)
}
ctx := t.Context()
if u, ok, err := p.realtime.User(ctx, 42); err != nil || !ok || u.Name == nil || *u.Name != "Ada" {
t.Fatalf("User(42) = %+v, %v, %v", u, ok, err)
}
room, ok := p.realtime.Registry().Get("room")
if !ok {
t.Fatal("no room authorizer")
}
if !room.Authorize(ctx, 42, "room:7").Allowed || room.Authorize(ctx, 42, "room:8").Reason() != "not a room member" {
t.Fatal("room authorizer does not follow membership")
}
var lines []string
if err := p.Routes(routeRecorder{lines: &lines}); err != nil {
t.Fatal(err)
}
want := []string{
"GET /api/realtime/token jwt.auth,throttle:acme-realtime",
"POST /api/realtime/subscribe raw,throttle:acme-realtime",
}
if !slices.Equal(lines, want) {
t.Fatalf("routes = %q, want %q", lines, want)
}
}
func ExampleMemoryDriver() {
app, err := newApp(map[string]any{"realtime.driver": "memory"})
if err != nil {
fmt.Println(err)
return
}
svc, err := lighthouse.From(app)
if err != nil {
fmt.Println(err)
return
}
// Code under test publishes; here the example calls the driver itself.
ctx := context.Background()
_ = svc.Driver().Publish(ctx, "blog:7", "blog.post_updated", json.RawMessage(`{"id":1}`))
_ = svc.Driver().Broadcast(ctx, []string{"blog:7", "blog:8"}, "blog.posts_imported", json.RawMessage(`{"count":3}`))
// docs:start publications
mem := svc.Driver().(*lighthouse.MemoryDriver)
for _, pub := range mem.Publications() {
fmt.Println(pub.Method, pub.Channels, pub.Event)
}
// docs:end publications
// Output:
// publish [blog:7] blog.post_updated
// broadcast [blog:7 blog:8] blog.posts_imported
}