docs(flare,kiosk,lagoon): compile README Go examples via src= (quick-261118-qsd)

- flare: send region run by TestDocsNotifyReply against a loopback TLS push
  service; blogSubscriptions and the publish-source region run by
  TestDocsSubscriptionSource on a Postgres container (skips under -short)
- kiosk: write, newest and client regions run by TestDocsWriteManifest (a
  copy of the literal fixture), ExampleVersionsResponse and
  TestDocsBlogReleases (httptest registry); the CheckT fence reuses
  TestPluginManifest
- lagoon: new open region run by TestDocsOpenFromApp (DocsDSN added to
  export_docs_test.go); the model, create-post, on-database, publish and
  migrations fences reuse the Database pages' targets
This commit is contained in:
Jakub Zych
2026-11-18 19:53:27 +01:00
parent d04454c57b
commit c517db564c
7 changed files with 535 additions and 63 deletions

View File

@@ -43,10 +43,10 @@ Use cases:
Send a push to one stored subscription:
```go
```go src=modules/flare/example_test.go#send
svc, err := flare.From(app)
if err != nil {
return err
return false, err
}
payload := []byte(`{"title":"New comment","body":"Someone replied to your post"}`)
err = svc.Pusher().Send(ctx, flare.Subscription{
@@ -56,24 +56,29 @@ err = svc.Pusher().Send(ctx, flare.Subscription{
}, payload, flare.SendOptions{Urgency: "normal"})
if errors.Is(err, flare.ErrSubscriptionGone) {
// The browser unsubscribed: delete the row.
return true, nil
}
```
Publish a subscription source from a plugin's `Boot`, so operator commands can read the stored subscriptions of a user:
```go
```go src=modules/flare/example_test.go#blogSubscriptions
// blogSubscriptions reads the blog's stored push subscriptions for
// operator commands such as websockets:test-push.
type blogSubscriptions struct{ db *gorm.DB }
```
```go src=modules/flare/example_test.go#blogSubscriptions.Subscriptions
func (s blogSubscriptions) Subscriptions(ctx context.Context, userID uint) ([]flare.SubscriptionInfo, error) {
var user models.User
var user User
if err := s.db.WithContext(ctx).First(&user, userID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, flare.ErrUserNotFound
}
return nil, err
}
var rows []models.PushSubscription
if err := s.db.WithContext(ctx).Where("user_id = ?", userID).Find(&rows).Error; err != nil {
var rows []PushSubscription
if err := s.db.WithContext(ctx).Where("user_id = ?", userID).Order("id").Find(&rows).Error; err != nil {
return nil, err
}
out := make([]flare.SubscriptionInfo, 0, len(rows))
@@ -87,8 +92,9 @@ func (s blogSubscriptions) Subscriptions(ctx context.Context, userID uint) ([]fl
}
return out, nil
}
```
// In Boot:
```go src=modules/flare/example_test.go#publish-source
if err := app.Publish[flare.SubscriptionSource](blogSubscriptions{db: gdb}); err != nil {
return err
}
@@ -148,4 +154,4 @@ Both commands print their own failure messages and return `bonfire.Reported` err
go test ./modules/flare/...
```
`TestRFC8291AppendixA` fixes the RFC's salt and application server key and compares the output with the RFC's published bytes. The send tests run an `httptest.NewTLSServer` push service with `127.0.0.1` in the allowlist; it verifies the VAPID token with the key from `k=` and decrypts the body as a browser would. Pass the test server's client to `flare.NewVAPIDPusher` or `flare.Service.SetHTTPClient` so it trusts the test certificate.
`TestRFC8291AppendixA` fixes the RFC's salt and application server key and compares the output with the RFC's published bytes. The send tests run an `httptest.NewTLSServer` push service with `127.0.0.1` in the allowlist; it verifies the VAPID token with the key from `k=` and decrypts the body as a browser would. Pass the test server's client to `flare.NewVAPIDPusher` or `flare.Service.SetHTTPClient` so it trusts the test certificate. `TestDocsSubscriptionSource` runs the subscription source shown above on a Postgres container and skips under `-short`.

View File

@@ -4,15 +4,24 @@ import (
"context"
"crypto/ecdh"
"crypto/rand"
"database/sql"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/flare"
"git.golem15.com/golem15/summercms/modules/lagoon"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"gorm.io/gorm"
)
// browserSubscription stands in for the PushSubscription a browser posts to
@@ -110,3 +119,192 @@ func ExampleHostAllowed() {
// push.apple.com false
// evil.example false
}
// User is the blog's user model, as much as the examples need.
type User struct {
ID uint `gorm:"column:id;primaryKey"`
}
func (User) TableName() string { return "acme_blog_users" }
// PushSubscription is a browser push subscription the blog stored.
type PushSubscription struct {
ID uint `gorm:"column:id;primaryKey"`
UserID uint `gorm:"column:user_id"`
Endpoint string `gorm:"column:endpoint"`
P256dh string `gorm:"column:p256dh"`
Auth string `gorm:"column:auth"`
UserAgent string `gorm:"column:user_agent"`
CreatedAt time.Time `gorm:"column:created_at"`
}
func (PushSubscription) TableName() string { return "acme_blog_push_subscriptions" }
// notifyReply pushes a reply notice to one stored subscription and reports
// whether the browser dropped it.
func notifyReply(ctx context.Context, app *backpack.App, row PushSubscription) (gone bool, err error) {
// docs:start send
svc, err := flare.From(app)
if err != nil {
return false, err
}
payload := []byte(`{"title":"New comment","body":"Someone replied to your post"}`)
err = svc.Pusher().Send(ctx, flare.Subscription{
Endpoint: row.Endpoint,
P256dh: row.P256dh,
Auth: row.Auth,
}, payload, flare.SendOptions{Urgency: "normal"})
if errors.Is(err, flare.ErrSubscriptionGone) {
// The browser unsubscribed: delete the row.
return true, nil
}
// docs:end send
return false, err
}
// TestDocsNotifyReply runs notifyReply on an app whose push.* config allows
// a stand-in push service on loopback.
func TestDocsNotifyReply(t *testing.T) {
push := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/gone" {
w.WriteHeader(http.StatusGone)
return
}
w.WriteHeader(http.StatusCreated)
}))
defer push.Close()
keys, err := flare.GenerateVAPIDKeys()
if err != nil {
t.Fatal(err)
}
cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Environ: []string{}})
if err != nil {
t.Fatal(err)
}
for k, v := range map[string]any{
"push.enabled": true,
"push.public_key": keys.PublicKey,
"push.private_key": keys.PrivateKey,
"push.subject": "mailto:admin@example.com",
"push.allowed_hosts": []string{"127.0.0.1"},
} {
if err := cfg.Set(k, v); err != nil {
t.Fatal(err)
}
}
app := backpack.New(cfg)
svc, err := flare.From(app)
if err != nil {
t.Fatal(err)
}
svc.SetHTTPClient(push.Client()) // trust the test server's certificate
for path, wantGone := range map[string]bool{"/live": false, "/gone": true} {
sub, err := browserSubscription(push.URL + path)
if err != nil {
t.Fatal(err)
}
gone, err := notifyReply(t.Context(), app, PushSubscription{Endpoint: sub.Endpoint, P256dh: sub.P256dh, Auth: sub.Auth})
if err != nil || gone != wantGone {
t.Fatalf("%s: gone = %v, %v", path, gone, err)
}
}
}
// blogSubscriptions reads the blog's stored push subscriptions for
// operator commands such as websockets:test-push.
type blogSubscriptions struct{ db *gorm.DB }
func (s blogSubscriptions) Subscriptions(ctx context.Context, userID uint) ([]flare.SubscriptionInfo, error) {
var user User
if err := s.db.WithContext(ctx).First(&user, userID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, flare.ErrUserNotFound
}
return nil, err
}
var rows []PushSubscription
if err := s.db.WithContext(ctx).Where("user_id = ?", userID).Order("id").Find(&rows).Error; err != nil {
return nil, err
}
out := make([]flare.SubscriptionInfo, 0, len(rows))
for _, r := range rows {
out = append(out, flare.SubscriptionInfo{
Subscription: flare.Subscription{Endpoint: r.Endpoint, P256dh: r.P256dh, Auth: r.Auth},
ID: r.ID,
UserAgent: r.UserAgent,
SubscribedAt: &r.CreatedAt,
})
}
return out, nil
}
// publishSubscriptions is the part of the blog plugin's Boot that hands
// its subscriptions to flare.
func publishSubscriptions(app *backpack.App, gdb *gorm.DB) error {
// docs:start publish-source
if err := app.Publish[flare.SubscriptionSource](blogSubscriptions{db: gdb}); err != nil {
return err
}
// docs:end publish-source
return nil
}
// TestDocsSubscriptionSource runs blogSubscriptions on a Postgres container:
// the published source lists a user's subscriptions and reports an unknown
// user as flare.ErrUserNotFound. It needs Docker and skips under -short.
func TestDocsSubscriptionSource(t *testing.T) {
if testing.Short() {
t.Skip("needs Docker (Postgres)")
}
ctx := t.Context()
ctr, err := postgres.Run(ctx, "postgres:16-alpine",
postgres.WithDatabase("flare"), postgres.WithUsername("flare"), postgres.WithPassword("flare"),
postgres.BasicWaitStrategies())
testcontainers.CleanupContainer(t, ctr)
if err != nil {
t.Fatal(err)
}
dsn, err := ctr.ConnectionString(ctx, "sslmode=disable")
if err != nil {
t.Fatal(err)
}
sqlDB, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = sqlDB.Close() })
gdb, err := lagoon.Use(ctx, sqlDB)
if err != nil {
t.Fatal(err)
}
for _, stmt := range []string{
`CREATE TABLE acme_blog_users (id SERIAL PRIMARY KEY)`,
`CREATE TABLE acme_blog_push_subscriptions (id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL, endpoint TEXT NOT NULL,
p256dh TEXT NOT NULL, auth TEXT NOT NULL, user_agent TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL)`,
`INSERT INTO acme_blog_users (id) VALUES (7)`,
`INSERT INTO acme_blog_push_subscriptions (user_id, endpoint, p256dh, auth, user_agent, created_at) VALUES
(7, 'https://fcm.googleapis.com/fcm/send/a', 'p1', 'a1', 'Firefox', now()),
(7, 'https://fcm.googleapis.com/fcm/send/b', 'p2', 'a2', 'Chrome', now())`,
} {
if err := gdb.Exec(stmt).Error; err != nil {
t.Fatal(err)
}
}
app := backpack.New(nil)
if err := publishSubscriptions(app, gdb); err != nil {
t.Fatal(err)
}
source, ok := app.Lookup[flare.SubscriptionSource]()
if !ok {
t.Fatal("no flare.SubscriptionSource published")
}
subs, err := source.Subscriptions(ctx, 7)
if err != nil || len(subs) != 2 || subs[0].UserAgent != "Firefox" || subs[1].Endpoint != "https://fcm.googleapis.com/fcm/send/b" || subs[0].SubscribedAt == nil {
t.Fatalf("Subscriptions(7) = %+v, %v", subs, err)
}
if _, err := source.Subscriptions(ctx, 8); !errors.Is(err, flare.ErrUserNotFound) {
t.Fatalf("Subscriptions(8) error = %v, want ErrUserNotFound", err)
}
}