docs(cabana,compass,conga): compile README Go examples via src= (quick-261118-qsd)
- cabana: the hand-written controller fence points at Post, PostsController and BlogPlugin declarations; TestDocsDeclarations now calls each of them - compass: mailSettings and ExampleOpen; the YAML block matches the directory ExampleOpen writes - conga: job, dispatch and progress fences reuse the Jobs page targets; new reindex and worker regions run in TestDocsDispatch (Docker), and the schedule fence is FeedPlugin.Schedule, checked by TestDocsSchedule
This commit is contained in:
@@ -43,99 +43,109 @@ Use cases:
|
||||
|
||||
## Usage
|
||||
|
||||
A plugin declares a job:
|
||||
|
||||
```go
|
||||
package blog
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/conga"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
A plugin declares a job's arguments and kind:
|
||||
|
||||
```go src=modules/conga/example_test.go#ImportPostsArgs
|
||||
// ImportPostsArgs are the arguments of the acme.blog post import job.
|
||||
type ImportPostsArgs struct {
|
||||
File string `json:"file"`
|
||||
}
|
||||
```
|
||||
|
||||
```go src=modules/conga/example_test.go#ImportPostsArgs.Kind
|
||||
// Kind names the job. It must be unique across the application.
|
||||
func (ImportPostsArgs) Kind() string { return "acme_blog_import_posts" }
|
||||
```
|
||||
|
||||
func ImportPostsJob(m *conga.Manager) pact.Job {
|
||||
return conga.Job(func(ctx context.Context, args ImportPostsArgs) error {
|
||||
id, _ := conga.JobID(ctx)
|
||||
// ... import args.File ...
|
||||
return m.CompleteJob(ctx, id, nil)
|
||||
}, conga.OnQueue("imports"))
|
||||
lists its jobs, so every worker registers them:
|
||||
|
||||
```go src=modules/conga/example_test.go#BlogPlugin.Jobs
|
||||
// Jobs returns the plugin's background jobs; every worker registers them.
|
||||
func (p *BlogPlugin) Jobs() []pact.Job {
|
||||
return []pact.Job{ImportPostsJob(p.jobs)}
|
||||
}
|
||||
```
|
||||
|
||||
and dispatches it inside the write that needs it:
|
||||
|
||||
```go
|
||||
func startImport(ctx context.Context, app *backpack.App, gdb *gorm.DB, file string) (uint, error) {
|
||||
m, err := conga.From(app)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var id uint
|
||||
err = gdb.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// ... write the import record ...
|
||||
id, err = m.Dispatch(ctx, tx, ImportPostsArgs{File: file}, conga.DispatchOpts{Label: "Import posts", Count: 100})
|
||||
return err
|
||||
})
|
||||
return id, err
|
||||
```go src=modules/conga/example_test.go#dispatch
|
||||
m, err := conga.From(app)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var id uint
|
||||
err = db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// ... write the import's own records on tx ...
|
||||
id, err = m.Dispatch(ctx, tx, ImportPostsArgs{File: file}, conga.DispatchOpts{
|
||||
Label: "Import posts",
|
||||
Count: 1,
|
||||
})
|
||||
return err
|
||||
})
|
||||
return id, err
|
||||
```
|
||||
|
||||
A long job reports progress and honours cancellation between items:
|
||||
|
||||
```go
|
||||
func importPosts(ctx context.Context, m *conga.Manager, files []string) error {
|
||||
id, _ := conga.JobID(ctx)
|
||||
if err := m.StartJob(ctx, id, len(files)); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, f := range files {
|
||||
if canceled, err := m.CheckIfCanceled(ctx, id); err != nil || canceled {
|
||||
```go src=modules/conga/example_test.go#ImportPostsJob
|
||||
// ImportPostsJob is the acme.blog import job. It reports progress on its
|
||||
// summer_jobs row, stops when the row is cancelled and completes the row.
|
||||
func ImportPostsJob(m *conga.Manager) pact.Job {
|
||||
return conga.Job(func(ctx context.Context, args ImportPostsArgs) error {
|
||||
id, _ := conga.JobID(ctx)
|
||||
rows := []string{args.File} // ... read the rows of args.File ...
|
||||
if err := m.StartJob(ctx, id, len(rows)); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range rows {
|
||||
canceled, err := m.CheckIfCanceled(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return m.StopJob(ctx, id, nil)
|
||||
if canceled {
|
||||
return m.StopJob(ctx, id, nil)
|
||||
}
|
||||
// ... import rows[i] ...
|
||||
if err := m.UpdateJobState(ctx, id, i+1, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// ... import f ...
|
||||
_ = f
|
||||
if err := m.UpdateJobState(ctx, id, i+1, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return m.CompleteJob(ctx, id, map[string]any{"imported": len(files)})
|
||||
return m.CompleteJob(ctx, id, map[string]any{"imported": len(rows)})
|
||||
}, conga.OnQueue("imports"))
|
||||
}
|
||||
```
|
||||
|
||||
A plugin schedules one of its registered commands; the worker runs it:
|
||||
|
||||
```go
|
||||
var _ pact.HasSchedule = (*Plugin)(nil)
|
||||
|
||||
func (p *Plugin) Schedule() []pact.ScheduledCommand {
|
||||
```go src=modules/conga/example_test.go#FeedPlugin.Schedule
|
||||
// Schedule runs two of the plugin's registered console commands.
|
||||
func (p *FeedPlugin) Schedule() []pact.ScheduledCommand {
|
||||
return []pact.ScheduledCommand{
|
||||
{Command: "blog:prune-drafts", Cadence: pact.Daily()},
|
||||
{Command: "blog:sync-feed", Args: []string{"--quiet"}, Cadence: pact.Every(15 * time.Minute)},
|
||||
{Command: "feed:prune", Cadence: pact.Daily()},
|
||||
{Command: "feed:sync", Args: []string{"--quiet"}, Cadence: pact.Every(15 * time.Minute)},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A job whose worker ships in a later release can already be queued from a request, on a queue that nothing serves yet. It waits there until a release registers its worker and the queue becomes served:
|
||||
|
||||
```go
|
||||
```go src=modules/conga/example_test.go#ReindexArgs
|
||||
// ReindexArgs are the arguments of the acme.reindex job, whose worker ships
|
||||
// in a later release.
|
||||
type ReindexArgs struct {
|
||||
SiteID int `json:"site_id"`
|
||||
}
|
||||
```
|
||||
|
||||
```go src=modules/conga/example_test.go#reindex
|
||||
// No plugin registers acme.reindex yet; its queue is served by nobody.
|
||||
_, err := m.Dispatch(ctx, tx, ReindexArgs{SiteID: 7}, conga.DispatchOpts{
|
||||
id, err := m.Dispatch(ctx, tx, ReindexArgs{SiteID: 7}, conga.DispatchOpts{
|
||||
Label: "acme.reindex",
|
||||
Queue: "acme_reindex",
|
||||
})
|
||||
if errors.Is(err, conga.ErrUnregisteredKindQueue) {
|
||||
// the queue is empty or a worker serves it
|
||||
return 0, fmt.Errorf("acme.reindex cannot wait: %w", err)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -143,7 +153,7 @@ Queue names follow River's rule: lowercase letters and digits, separated by `_`
|
||||
|
||||
A worker runs in the same process or in a separate one:
|
||||
|
||||
```go
|
||||
```go src=modules/conga/example_test.go#worker
|
||||
w, err := conga.StartWorker(ctx, app, plugins, conga.WorkerOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -2,6 +2,7 @@ package conga_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -127,9 +128,49 @@ func importStatus(ctx context.Context, m *conga.Manager, id uint) (string, error
|
||||
// docs:end status
|
||||
}
|
||||
|
||||
// TestDocsDispatch runs the dispatch region of the Jobs page on the
|
||||
// package's Postgres harness: a worker registers the plugin's job, the job
|
||||
// is dispatched in a transaction and completes its row.
|
||||
// ReindexArgs are the arguments of the acme.reindex job, whose worker ships
|
||||
// in a later release.
|
||||
type ReindexArgs struct {
|
||||
SiteID int `json:"site_id"`
|
||||
}
|
||||
|
||||
// Kind names the job.
|
||||
func (ReindexArgs) Kind() string { return "acme_reindex" }
|
||||
|
||||
// queueReindex queues the acme.reindex job in the transaction tx, before
|
||||
// any plugin registers its worker.
|
||||
func queueReindex(ctx context.Context, m *conga.Manager, tx *gorm.DB) (uint, error) {
|
||||
// docs:start reindex
|
||||
// No plugin registers acme.reindex yet; its queue is served by nobody.
|
||||
id, err := m.Dispatch(ctx, tx, ReindexArgs{SiteID: 7}, conga.DispatchOpts{
|
||||
Label: "acme.reindex",
|
||||
Queue: "acme_reindex",
|
||||
})
|
||||
if errors.Is(err, conga.ErrUnregisteredKindQueue) {
|
||||
// the queue is empty or a worker serves it
|
||||
return 0, fmt.Errorf("acme.reindex cannot wait: %w", err)
|
||||
}
|
||||
// docs:end reindex
|
||||
return id, err
|
||||
}
|
||||
|
||||
// runWorker starts a worker for the plugins' jobs, runs fn while it works
|
||||
// and stops it.
|
||||
func runWorker(ctx context.Context, app *backpack.App, plugins []party.Plugin, fn func() error) error {
|
||||
// docs:start worker
|
||||
w, err := conga.StartWorker(ctx, app, plugins, conga.WorkerOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer w.Stop(context.Background())
|
||||
// docs:end worker
|
||||
return fn()
|
||||
}
|
||||
|
||||
// TestDocsDispatch runs the dispatch, reindex and worker regions of the Jobs
|
||||
// page and the README on the package's Postgres harness: a worker registers
|
||||
// the plugin's job, the job is dispatched in a transaction and completes its
|
||||
// row, and a job without a registered worker waits on its own queue.
|
||||
func TestDocsDispatch(t *testing.T) {
|
||||
app, db := conga.DocsApp(t)
|
||||
plugin := &BlogPlugin{}
|
||||
@@ -139,39 +180,80 @@ func TestDocsDispatch(t *testing.T) {
|
||||
if n := len(plugin.Jobs()); n != 1 {
|
||||
t.Fatalf("Jobs() = %d jobs, want 1", n)
|
||||
}
|
||||
w, err := conga.StartWorker(t.Context(), app, []party.Plugin{plugin}, conga.WorkerOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := w.Stop(ctx); err != nil {
|
||||
t.Errorf("stop worker: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
id, err := startImport(t.Context(), app, db, "posts.csv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m, err := conga.From(app)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
for {
|
||||
got, err := importStatus(t.Context(), m, id)
|
||||
err = runWorker(t.Context(), app, []party.Plugin{plugin}, func() error {
|
||||
id, err := startImport(t.Context(), app, db, "posts.csv")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return err
|
||||
}
|
||||
if got == "Import posts: done (1/1)" {
|
||||
return
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
for {
|
||||
got, err := importStatus(t.Context(), m, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if got == "Import posts: done (1/1)" {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return fmt.Errorf("status = %q, want the job to complete", got)
|
||||
}
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("status = %q, want the job to complete", got)
|
||||
|
||||
var reindex uint
|
||||
if err := db.WithContext(t.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
reindex, err = queueReindex(t.Context(), m, tx)
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
rec, err := m.Get(t.Context(), reindex)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rec.Label != "acme.reindex" || rec.Status == conga.StatusComplete {
|
||||
return fmt.Errorf("reindex row = %+v, want it waiting", rec)
|
||||
}
|
||||
// The imports queue is served, so the unregistered kind is refused.
|
||||
_, err = m.Dispatch(t.Context(), db, ReindexArgs{SiteID: 7}, conga.DispatchOpts{Label: "acme.reindex", Queue: "imports"})
|
||||
if !errors.Is(err, conga.ErrUnregisteredKindQueue) {
|
||||
return fmt.Errorf("dispatch on a served queue = %v, want ErrUnregisteredKindQueue", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// FeedPlugin is the acme.feed plugin; only its schedule is shown here.
|
||||
type FeedPlugin struct{}
|
||||
|
||||
var _ pact.HasSchedule = (*FeedPlugin)(nil)
|
||||
|
||||
// Schedule runs two of the plugin's registered console commands.
|
||||
func (p *FeedPlugin) Schedule() []pact.ScheduledCommand {
|
||||
return []pact.ScheduledCommand{
|
||||
{Command: "feed:prune", Cadence: pact.Daily()},
|
||||
{Command: "feed:sync", Args: []string{"--quiet"}, Cadence: pact.Every(15 * time.Minute)},
|
||||
}
|
||||
}
|
||||
|
||||
// TestDocsSchedule checks the schedule the README shows.
|
||||
func TestDocsSchedule(t *testing.T) {
|
||||
entries := (&FeedPlugin{}).Schedule()
|
||||
if len(entries) != 2 {
|
||||
t.Fatalf("Schedule() = %+v", entries)
|
||||
}
|
||||
if h, m, daily := entries[0].Cadence.At(); entries[0].Command != "feed:prune" || !daily || h != 0 || m != 0 {
|
||||
t.Fatalf("entry 0 = %+v", entries[0])
|
||||
}
|
||||
if e := entries[1]; e.Command != "feed:sync" || len(e.Args) != 1 || e.Args[0] != "--quiet" || e.Cadence.Interval() != 15*time.Minute {
|
||||
t.Fatalf("entry 1 = %+v", e)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user