docs(lighthouse,postcard,signpost): compile README Go examples via src= (quick-261118-qsd)
This commit is contained in:
@@ -79,18 +79,10 @@ centrifugo:
|
||||
|
||||
A plugin imports the driver package for its side effect, builds the service at Boot, installs a user lookup and registers its channel authorizers:
|
||||
|
||||
```go
|
||||
package acme
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/lighthouse"
|
||||
_ "git.golem15.com/golem15/summercms/modules/lighthouse/centrifugo"
|
||||
)
|
||||
|
||||
func (p *Plugin) Boot(app *backpack.App) error {
|
||||
```go src=modules/lighthouse/example_test.go#RoomsPlugin.Boot
|
||||
// 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
|
||||
@@ -112,8 +104,9 @@ func (p *Plugin) Boot(app *backpack.App) error {
|
||||
|
||||
and mounts the driver's routes once:
|
||||
|
||||
```go
|
||||
func (p *Plugin) Routes(r pact.Router) error {
|
||||
```go src=modules/lighthouse/example_test.go#RoomsPlugin.Routes
|
||||
// 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(),
|
||||
@@ -124,10 +117,10 @@ func (p *Plugin) Routes(r pact.Router) error {
|
||||
|
||||
A model package stays free of realtime code; the plugin binds the model at Boot:
|
||||
|
||||
```go
|
||||
err := lighthouse.Bind[models.Post](svc, lighthouse.Binding[models.Post]{
|
||||
```go src=modules/lighthouse/example_test.go#bind
|
||||
return lighthouse.Bind[Post](svc, lighthouse.Binding[Post]{
|
||||
Alias: "blog.post",
|
||||
Channels: func(ctx context.Context, tx *gorm.DB, p *models.Post) ([]string, error) {
|
||||
Channels: func(ctx context.Context, tx *gorm.DB, p *Post) ([]string, error) {
|
||||
return []string{"blog:" + strconv.FormatUint(uint64(p.BlogID), 10)}, nil
|
||||
},
|
||||
})
|
||||
@@ -135,21 +128,20 @@ err := lighthouse.Bind[models.Post](svc, lighthouse.Binding[models.Post]{
|
||||
|
||||
A bulk import suppresses the per-row events and publishes one summary after commit:
|
||||
|
||||
```go
|
||||
err := lighthouse.WithoutBroadcasting[models.Post](ctx, func(ctx context.Context) error {
|
||||
return lagoon.Transaction(ctx, gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||
for _, p := range posts {
|
||||
if err := tx.Create(&p).Error; err != nil {
|
||||
```go src=modules/lighthouse/example_test.go#bulk
|
||||
return lighthouse.WithoutBroadcasting[Post](ctx, func(ctx context.Context) error {
|
||||
return lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||
for _, title := range titles {
|
||||
if err := tx.Create(&Post{BlogID: 7, Title: title}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return svc.Emit(ctx, tx, lighthouse.Broadcast{
|
||||
Channels: []string{"blog:7"},
|
||||
Event: "blog.bulk_updated",
|
||||
Event: "blog.posts_imported",
|
||||
Payload: struct {
|
||||
Reason string `json:"reason"`
|
||||
Count int `json:"count"`
|
||||
}{"import", len(posts)},
|
||||
Count int `json:"count"`
|
||||
}{len(titles)},
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -157,7 +149,7 @@ err := lighthouse.WithoutBroadcasting[models.Post](ctx, func(ctx context.Context
|
||||
|
||||
Tests select the memory driver and read what was published:
|
||||
|
||||
```go
|
||||
```go src=modules/lighthouse/example_test.go#publications
|
||||
mem := svc.Driver().(*lighthouse.MemoryDriver)
|
||||
for _, pub := range mem.Publications() {
|
||||
fmt.Println(pub.Method, pub.Channels, pub.Event)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -62,7 +62,9 @@ func TestFromSelectsDriver(t *testing.T) {
|
||||
}
|
||||
t.Run("unknown_lists_registered", func(t *testing.T) {
|
||||
_, err := From(configApp(t, map[string]any{"realtime.driver": "nope"}))
|
||||
if err == nil || !strings.Contains(err.Error(), `unknown realtime.driver "nope"`) || !strings.Contains(err.Error(), "acme-nil-driver, log, memory, null") {
|
||||
// example_test.go imports lighthouse/centrifugo, so "centrifugo" may
|
||||
// sit between the drivers this package's tests register.
|
||||
if err == nil || !strings.Contains(err.Error(), `unknown realtime.driver "nope"`) || !strings.Contains(err.Error(), "acme-nil-driver, ") || !strings.Contains(err.Error(), "log, memory, null") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user