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

@@ -48,7 +48,7 @@ Use cases:
Open the shared pool once at boot and publish it, so plugins and handlers reuse the same handles:
```go
```go src=modules/lagoon/example_test.go#open
sqlDB, gdb, err := lagoon.OpenFromApp(ctx, app)
if err != nil {
return err
@@ -58,68 +58,123 @@ if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
}
```
A model uses the column types and helpers directly:
A model uses the column types directly, and a handler validates and mass-assigns input through the helpers:
```go
```go src=modules/lagoon/example_test.go#Post
// Post is the acme.blog post model: a plain GORM struct with lagoon column
// types.
type Post struct {
ID uint `gorm:"column:id;primaryKey"`
Title string `gorm:"column:title"`
Tags lagoon.Jsonable[[]string] `gorm:"column:tags"`
APIToken lagoon.Encrypted `gorm:"column:api_token"`
}
ID uint `gorm:"column:id;primaryKey" json:"id"`
Title string `gorm:"column:title" json:"title"`
Slug string `gorm:"column:slug" json:"slug"`
Views int `gorm:"column:views" json:"views"`
Tags lagoon.Jsonable[[]string] `gorm:"column:tags" json:"-"`
APIToken lagoon.Encrypted `gorm:"column:api_token" json:"-"`
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at" json:"-"`
func (Post) Fillable() []string { return []string{"title"} }
func createPost(ctx context.Context, gdb *gorm.DB, tr *phrasebook.Translator, input map[string]any) (map[string][]string, error) {
var post Post
rules := map[string]string{"title": "required|max:255|unique:posts"}
if errs, err := lagoon.Validate(ctx, gdb, &post, rules, input, tr); err != nil || errs != nil {
return errs, err
}
if err := lagoon.Fill(&post, post.Fillable(), input, false); err != nil {
return nil, err
}
post.APIToken = lagoon.NewEncrypted("change-me")
return nil, gdb.Create(&post).Error
Categories []Category `gorm:"many2many:acme_blog_post_categories" json:"-"`
}
```
```go src=modules/lagoon/example_test.go#Post.Fillable
// Fillable is the Go form of $fillable: the keys mass assignment may set.
func (Post) Fillable() []string { return []string{"title", "views"} }
```
```go src=modules/lagoon/example_test.go#create-post
rules := map[string]string{
"title": "required|max:255|unique:acme_blog_posts",
"views": "nullable|integer|min:0",
}
var post Post
errs, err := lagoon.Validate(ctx, db, &post, rules, input, nil)
if err != nil || errs != nil {
return nil, errs, err
}
if err := lagoon.Fill(&post, post.Fillable(), input, false); err != nil {
return nil, nil, err
}
if err := db.WithContext(ctx).Create(&post).Error; err != nil {
return nil, nil, err
}
return &post, nil, nil
```
A plugin registers its GORM callbacks from Boot through `lagoon.OnDatabase`, so they are installed whenever the database is published, and defers side effects until the write commits. Register the callback before GORM's `gorm:commit_or_rollback_transaction` step: lagoon runs a single-statement write's after-commit work from `lagoon:after_commit` right after that step, so work buffered by a callback GORM sorts later never runs, and `lagoon.AfterCommit` logs a warning for it (see [Callbacks registered at boot](../../docs/database/transactions.md#callbacks-registered-at-boot)):
```go
func (p *Plugin) Boot(app *backpack.App) error {
return lagoon.OnDatabase(app, func(_ *sql.DB, gdb *gorm.DB) error {
return gdb.Callback().Create().After("gorm:create").Before("gorm:commit_or_rollback_transaction").Register("acme:post_created", func(db *gorm.DB) {
if db.Error != nil {
return
}
lagoon.AfterCommit(db.Statement.Context, db, func(ctx context.Context, db *gorm.DB) {
// runs only once the insert is committed
})
```go src=modules/lagoon/example_test.go#on-database
return lagoon.OnDatabase(app, func(_ *sql.DB, gdb *gorm.DB) error {
return gdb.Callback().Create().After("gorm:create").Before("gorm:commit_or_rollback_transaction").Register("acme:post_created", func(db *gorm.DB) {
post, ok := db.Statement.Dest.(*Post)
if db.Error != nil || !ok {
return
}
lagoon.AfterCommit(db.Statement.Context, db, func(ctx context.Context, db *gorm.DB) {
*log = append(*log, "created "+post.Slug) // runs only once the insert is committed
})
})
}
})
```
func publish(ctx context.Context, gdb *gorm.DB, post *Post) error {
return lagoon.Transaction(ctx, gdb, func(ctx context.Context, tx *gorm.DB) error {
return tx.Create(post).Error // acme:post_created work waits for this commit
```go src=modules/lagoon/example_test.go#publish
return lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
if err := tx.Model(&Post{}).Where("id = ?", id).Update("title", "Published").Error; err != nil {
return err
}
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, db *gorm.DB) {
*log = append(*log, fmt.Sprintf("post %d published", id)) // broadcast, index, send mail...
})
}
if fail {
return errors.New("rolled back") // the AfterCommit work never runs
}
return nil
})
```
A plugin ships its schema as an ordered gormigrate set; `migrate` runs it after the framework sets:
```go
func (p *Plugin) Migrations() []*gormigrate.Migration {
return []*gormigrate.Migration{{
ID: "202601010001_create_posts",
Migrate: func(tx *gorm.DB) error {
return tx.Exec(`CREATE TABLE posts (id SERIAL PRIMARY KEY, title TEXT NOT NULL, tags TEXT, api_token TEXT)`).Error
```go src=modules/lagoon/example_test.go#BlogPlugin.Migrations
// Migrations returns the plugin's schema as an ordered gormigrate set. In a
// scaffolded plugin each migration is a file in updates/ and this list is
// generated in file name order.
func (p *BlogPlugin) Migrations() []*gormigrate.Migration {
return []*gormigrate.Migration{
{
ID: "20260101000100_create_posts",
Migrate: func(tx *gorm.DB) error {
return tx.Exec(`CREATE TABLE acme_blog_posts (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
slug TEXT NOT NULL,
views INTEGER NOT NULL DEFAULT 0,
tags TEXT,
api_token TEXT,
deleted_at TIMESTAMPTZ
)`).Error
},
Rollback: func(tx *gorm.DB) error {
return tx.Exec(`DROP TABLE IF EXISTS acme_blog_posts`).Error
},
},
Rollback: func(tx *gorm.DB) error {
return tx.Exec(`DROP TABLE IF EXISTS posts`).Error
{
ID: "20260101000200_create_comments_and_categories",
Migrate: func(tx *gorm.DB) error {
for _, stmt := range []string{
`CREATE TABLE acme_blog_comments (id SERIAL PRIMARY KEY, post_id INTEGER NOT NULL, body TEXT NOT NULL, deleted_at TIMESTAMPTZ)`,
`CREATE TABLE acme_blog_categories (id SERIAL PRIMARY KEY, name TEXT NOT NULL)`,
`CREATE TABLE acme_blog_post_categories (post_id INTEGER NOT NULL, category_id INTEGER NOT NULL, sort_order INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (post_id, category_id))`,
} {
if err := tx.Exec(stmt).Error; err != nil {
return err
}
}
return nil
},
Rollback: func(tx *gorm.DB) error {
return tx.Exec(`DROP TABLE IF EXISTS acme_blog_post_categories, acme_blog_categories, acme_blog_comments`).Error
},
},
}}
}
}
```

View File

@@ -3,6 +3,7 @@ package lagoon_test
import (
"context"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -10,6 +11,7 @@ import (
"testing"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/lagoon"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/party"
@@ -645,3 +647,49 @@ func TestDocsModelDeclarations(t *testing.T) {
t.Fatalf("Migrations() = %d, want 2", n)
}
}
// openDatabase opens the shared pool from the app's config at boot and
// publishes it, so plugins and handlers reuse the same handles.
func openDatabase(ctx context.Context, app *backpack.App) error {
// docs:start open
sqlDB, gdb, err := lagoon.OpenFromApp(ctx, app)
if err != nil {
return err
}
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
return err
}
// docs:end open
return nil
}
// TestDocsOpenFromApp runs the open region on a config whose database.dsn
// and app.key come from the environment.
func TestDocsOpenFromApp(t *testing.T) {
dsn := lagoon.DocsDSN(t, "docs_open")
key := base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef"))
cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Environ: []string{
"SUMMER_DATABASE__DSN=" + dsn,
"SUMMER_APP__KEY=" + key,
}})
if err != nil {
t.Fatal(err)
}
app := backpack.New(cfg)
if err := openDatabase(t.Context(), app); err != nil {
t.Fatal(err)
}
sqlDB, ok := app.Lookup[*sql.DB]()
if !ok {
t.Fatal("no *sql.DB published")
}
t.Cleanup(func() { _ = sqlDB.Close() })
gdb, ok := app.Lookup[*gorm.DB]()
if !ok {
t.Fatal("no *gorm.DB published")
}
var one int
if err := gdb.WithContext(t.Context()).Raw(`SELECT 1`).Scan(&one).Error; err != nil || one != 1 {
t.Fatalf("SELECT 1 = %d, %v", one, err)
}
}

View File

@@ -19,3 +19,12 @@ func DocsDB(t *testing.T, name string) *gorm.DB {
}
return gdb
}
// DocsDSN returns the DSN of a fresh database named name in this package's
// Postgres harness, for the docs example that opens the pool from config.
// It skips under -short like DocsDB.
func DocsDSN(t *testing.T, name string) string {
t.Helper()
_, dsn := dedicatedDB(t, name)
return dsn
}