feat: real lastmod from record events and debounced rebuilds
- RecordSaved with a change outside golem15.sitemap.lastmod_ignore moves the lastmod of the record's rows (only the changed locale's for a translated change); a no-op save, an ignored change or a rebuild does not - RecordDeleted takes the record's rows out of the files at once - record events queue one rebuild per golem15.sitemap.rebuild_delay_seconds (rebuild_pending_until, P33-12); the job clears it when it starts - sitemap:rebuild [--queue], scheduled nightly at 03:00 (pact.HasSchedule)
This commit is contained in:
209
classes/lastmod.go
Normal file
209
classes/lastmod.go
Normal file
@@ -0,0 +1,209 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/conga"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// The config keys of the event-driven lastmod and the debounced rebuild.
|
||||
const (
|
||||
// LastmodIgnoreConfigKey lists the attributes whose change does not
|
||||
// move lastmod.
|
||||
LastmodIgnoreConfigKey = "golem15.sitemap.lastmod_ignore"
|
||||
// RebuildDelayConfigKey is the delay of the rebuild a record event
|
||||
// queues, in seconds.
|
||||
RebuildDelayConfigKey = "golem15.sitemap.rebuild_delay_seconds"
|
||||
)
|
||||
|
||||
// DefaultLastmodIgnore is the ignore list when the config has none.
|
||||
var DefaultLastmodIgnore = []string{"updated_at", "created_at", "views", "sort_order"}
|
||||
|
||||
// defaultRebuildDelay is the rebuild delay when the config has none.
|
||||
const defaultRebuildDelay = 60 * time.Second
|
||||
|
||||
// LastmodIgnore reads golem15.sitemap.lastmod_ignore: a list of attribute
|
||||
// names (or one comma-separated string); DefaultLastmodIgnore when unset.
|
||||
func LastmodIgnore(cfg *compass.Config) map[string]bool {
|
||||
names := DefaultLastmodIgnore
|
||||
if cfg != nil {
|
||||
if v, ok := cfg.Lookup(LastmodIgnoreConfigKey); ok && v != nil {
|
||||
names = nil
|
||||
switch list := v.(type) {
|
||||
case []any:
|
||||
for _, item := range list {
|
||||
names = append(names, fmt.Sprint(item))
|
||||
}
|
||||
case []string:
|
||||
names = list
|
||||
case string:
|
||||
names = strings.Split(list, ",")
|
||||
}
|
||||
}
|
||||
}
|
||||
out := make(map[string]bool, len(names))
|
||||
for _, n := range names {
|
||||
if n = strings.TrimSpace(n); n != "" {
|
||||
out[n] = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// RebuildDelay reads golem15.sitemap.rebuild_delay_seconds; 60 seconds when
|
||||
// unset, 0 or more when set.
|
||||
func RebuildDelay(cfg *compass.Config) time.Duration {
|
||||
if cfg == nil || !cfg.Has(RebuildDelayConfigKey) {
|
||||
return defaultRebuildDelay
|
||||
}
|
||||
if n := cfg.Int(RebuildDelayConfigKey); n > 0 {
|
||||
return time.Duration(n) * time.Second
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Changed is what a save changed for lastmod: Any when a change outside the
|
||||
// ignore list exists, All when one of them is on the record's own row
|
||||
// (every locale's address moves), else Locales names the translated
|
||||
// locales that changed.
|
||||
type Changed struct {
|
||||
Any bool
|
||||
All bool
|
||||
Locales map[string]bool
|
||||
}
|
||||
|
||||
// RealChanges filters a save's changes through the ignore list. A no-op
|
||||
// save (no changes) and one that changes only ignored attributes change
|
||||
// nothing (RESEARCH Pitfall 4).
|
||||
func RealChanges(changes []pact.RecordChange, ignore map[string]bool) Changed {
|
||||
out := Changed{Locales: map[string]bool{}}
|
||||
for _, c := range changes {
|
||||
if ignore[c.Attribute] {
|
||||
continue
|
||||
}
|
||||
out.Any = true
|
||||
if c.Locale == "" {
|
||||
out.All = true
|
||||
continue
|
||||
}
|
||||
out.Locales[c.Locale] = true
|
||||
}
|
||||
if out.All {
|
||||
out.Locales = map[string]bool{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// RecordSaved handles a saved record of a content type (D-30): when the
|
||||
// save changed an attribute outside golem15.sitemap.lastmod_ignore, the
|
||||
// lastmod of the record's rows moves to now (every locale's for a change
|
||||
// on the record's own row, else only the changed locales'), and a
|
||||
// debounced rebuild is queued. A model no content type declares is
|
||||
// ignored.
|
||||
func RecordSaved(ctx context.Context, app *backpack.App, ev *pact.RecordSaved) error {
|
||||
typ, db, ok := contentTypeOf(app, ev.Model)
|
||||
if !ok || ev == nil {
|
||||
return nil
|
||||
}
|
||||
changed := RealChanges(ev.Changes, LastmodIgnore(app.Config))
|
||||
if !changed.Any {
|
||||
return nil
|
||||
}
|
||||
db = db.WithContext(ctx)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
q := db.Model(&models.URL{}).Where("type_key = ? AND record_id = ?", typ, ev.ID)
|
||||
if !changed.All {
|
||||
locales := make([]string, 0, len(changed.Locales))
|
||||
for l := range changed.Locales {
|
||||
locales = append(locales, l)
|
||||
}
|
||||
q = q.Where("locale IN ?", locales)
|
||||
}
|
||||
if err := q.Updates(map[string]any{"lastmod": now, "updated_at": now}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return RequestDebouncedRebuild(ctx, app, db)
|
||||
}
|
||||
|
||||
// RecordDeleted handles a deleted record of a content type: its rows leave
|
||||
// the files at once (reason deleted, their file numbers kept as holes) and
|
||||
// a debounced rebuild is queued.
|
||||
func RecordDeleted(ctx context.Context, app *backpack.App, ev *pact.RecordDeleted) error {
|
||||
if ev == nil {
|
||||
return nil
|
||||
}
|
||||
typ, db, ok := contentTypeOf(app, ev.Model)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
db = db.WithContext(ctx)
|
||||
now := time.Now().UTC()
|
||||
if err := db.Model(&models.URL{}).
|
||||
Where("type_key = ? AND record_id = ? AND excluded_reason <> ?", typ, ev.ID, models.ReasonDeleted).
|
||||
Updates(map[string]any{"excluded_reason": models.ReasonDeleted, "updated_at": now}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return RequestDebouncedRebuild(ctx, app, db)
|
||||
}
|
||||
|
||||
// contentTypeOf finds the content type key of a record event's model and
|
||||
// the application database.
|
||||
func contentTypeOf(app *backpack.App, model string) (string, *gorm.DB, bool) {
|
||||
if app == nil {
|
||||
return "", nil, false
|
||||
}
|
||||
reg, ok := app.Lookup[*signpost.Registry]()
|
||||
if !ok || reg == nil {
|
||||
return "", nil, false
|
||||
}
|
||||
typ, ok := reg.ContentTypeForModel(model)
|
||||
if !ok || typ.Content == nil {
|
||||
return "", nil, false
|
||||
}
|
||||
db, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || db == nil {
|
||||
return "", nil, false
|
||||
}
|
||||
return typ.Key, db, true
|
||||
}
|
||||
|
||||
// RequestDebouncedRebuild queues one rebuild golem15.sitemap.rebuild_delay_seconds
|
||||
// from now unless one is already pending (P33-12): a conditional UPDATE of
|
||||
// rebuild_pending_until decides, and the job is enqueued in the same
|
||||
// transaction, so events within the delay share one rebuild. The job
|
||||
// clears the pending time when it starts.
|
||||
func RequestDebouncedRebuild(ctx context.Context, app *backpack.App, db *gorm.DB) error {
|
||||
delay := RebuildDelay(app.Config)
|
||||
m, err := conga.From(app)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
res := tx.Exec(`UPDATE golem15_sitemap_settings
|
||||
SET rebuild_pending_until = NOW() + make_interval(secs => ?)
|
||||
WHERE id = 1 AND (rebuild_pending_until IS NULL OR rebuild_pending_until <= NOW())`, delay.Seconds())
|
||||
if res.Error != nil || res.RowsAffected == 0 {
|
||||
return res.Error
|
||||
}
|
||||
return m.Enqueue(ctx, tx, RebuildArgs{}, conga.EnqueueOpts{Delay: delay})
|
||||
})
|
||||
}
|
||||
|
||||
// ClearPending ends the debounce window; the rebuild job calls it when it
|
||||
// starts, so events during the rebuild queue the next one.
|
||||
func ClearPending(ctx context.Context, app *backpack.App) error {
|
||||
db, ok := app.Lookup[*gorm.DB]()
|
||||
if !ok || db == nil {
|
||||
return ErrNoDatabase
|
||||
}
|
||||
return db.WithContext(ctx).Exec(`UPDATE golem15_sitemap_settings SET rebuild_pending_until = NULL WHERE id = 1`).Error
|
||||
}
|
||||
38
classes/lastmod_test.go
Normal file
38
classes/lastmod_test.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// TestRealChanges pins which saves move lastmod (D-30, RESEARCH Pitfall
|
||||
// 4): nothing for an empty or ignored-only change list; every locale for a
|
||||
// change on the record's own row; only the named locales for translated
|
||||
// changes.
|
||||
func TestRealChanges(t *testing.T) {
|
||||
ignore := map[string]bool{"updated_at": true, "views": true}
|
||||
for name, c := range map[string]struct {
|
||||
changes []pact.RecordChange
|
||||
any bool
|
||||
all bool
|
||||
locales []string
|
||||
}{
|
||||
"no-op save": {nil, false, false, nil},
|
||||
"ignored only": {[]pact.RecordChange{{Attribute: "updated_at"}, {Attribute: "views"}}, false, false, nil},
|
||||
"own row": {[]pact.RecordChange{{Attribute: "updated_at"}, {Attribute: "title"}}, true, true, nil},
|
||||
"translated": {[]pact.RecordChange{{Attribute: "title", Locale: "pl"}, {Attribute: "slug", Locale: "de"}}, true, false, []string{"de", "pl"}},
|
||||
"both": {[]pact.RecordChange{{Attribute: "title", Locale: "pl"}, {Attribute: "content"}}, true, true, nil},
|
||||
} {
|
||||
got := RealChanges(c.changes, ignore)
|
||||
if got.Any != c.any || got.All != c.all || len(got.Locales) != len(c.locales) {
|
||||
t.Errorf("%s: %+v", name, got)
|
||||
continue
|
||||
}
|
||||
for _, l := range c.locales {
|
||||
if !got.Locales[l] {
|
||||
t.Errorf("%s: locale %s missing in %+v", name, l, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
72
classes/slots_test.go
Normal file
72
classes/slots_test.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestAssignSlots pins stable numbering without a database (D-30, RESEARCH
|
||||
// Pitfall 5): appends fill the last file of their group, a left-out row
|
||||
// keeps its number as a hole, only a renumber packs the listed rows again,
|
||||
// and groups are numbered apart.
|
||||
func TestAssignSlots(t *testing.T) {
|
||||
t0 := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
|
||||
rows := []*Slot{}
|
||||
add := func(id uint64, grp string, at time.Duration) *Slot {
|
||||
s := &Slot{ID: id, Grp: grp, FirstSeen: t0.Add(at), Listed: true}
|
||||
rows = append(rows, s)
|
||||
return s
|
||||
}
|
||||
files := func(grp string) []int {
|
||||
var out []int
|
||||
for _, r := range rows {
|
||||
if r.Grp == grp && r.Listed && r.FileNo != nil {
|
||||
out = append(out, *r.FileNo)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
eq := func(a []int, b ...int) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
for i := uint64(1); i <= 5; i++ {
|
||||
add(i, "pages", 0)
|
||||
}
|
||||
add(9, "posts", 0)
|
||||
if !AssignSlots(rows, 2, true) || !eq(files("pages"), 1, 1, 2, 2, 3) || !eq(files("posts"), 1) {
|
||||
t.Fatalf("first numbering: pages %v posts %v", files("pages"), files("posts"))
|
||||
}
|
||||
if AssignSlots(rows, 2, false) {
|
||||
t.Fatal("a second pass changed numbers")
|
||||
}
|
||||
rows[1].Listed = false
|
||||
if AssignSlots(rows, 2, false) || !eq(files("pages"), 1, 2, 2, 3) || *rows[1].FileNo != 1 {
|
||||
t.Fatalf("after a delete: %v, hole %v", files("pages"), rows[1].FileNo)
|
||||
}
|
||||
add(6, "pages", time.Hour)
|
||||
add(7, "pages", 2*time.Hour)
|
||||
AssignSlots(rows, 2, false)
|
||||
if *rows[len(rows)-2].FileNo != 3 || *rows[len(rows)-1].FileNo != 4 {
|
||||
t.Fatalf("appends: %v %v", *rows[len(rows)-2].FileNo, *rows[len(rows)-1].FileNo)
|
||||
}
|
||||
AssignSlots(rows, 3, true)
|
||||
if !eq(files("pages"), 1, 1, 1, 2, 2, 2) || rows[1].FileNo != nil {
|
||||
t.Fatalf("renumber: %v, left-out row %v", files("pages"), rows[1].FileNo)
|
||||
}
|
||||
// A returning row fills its own hole when it still has one.
|
||||
rows[1].Listed = true
|
||||
n := 1
|
||||
rows[1].FileNo = &n
|
||||
AssignSlots(rows, 3, false)
|
||||
if *rows[1].FileNo != 1 {
|
||||
t.Fatalf("returning row moved to %d", *rows[1].FileNo)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,10 @@ package sitemap
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/golem15/summercms/modules/conga"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// TestCommandsDocumented logs every console command whose help lacks a
|
||||
@@ -19,3 +22,29 @@ func TestCommandsDocumented(t *testing.T) {
|
||||
t.Logf("%s", problem)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScheduleAndJobs pins the nightly sitemap:rebuild at 03:00, which must
|
||||
// name a registered command, and the rebuild job (kind
|
||||
// golem15.sitemap.rebuild, three attempts).
|
||||
func TestScheduleAndJobs(t *testing.T) {
|
||||
p := &Plugin{}
|
||||
entries := p.Schedule()
|
||||
if len(entries) != 1 || entries[0].Command != "sitemap:rebuild" || entries[0].Cadence != pact.DailyAt(3, 0) {
|
||||
t.Fatalf("schedule = %+v", entries)
|
||||
}
|
||||
found := false
|
||||
for _, c := range p.Commands() {
|
||||
found = found || c.Name == entries[0].Command
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("the scheduled command is not registered")
|
||||
}
|
||||
jobs := p.Jobs()
|
||||
if len(jobs) != 1 {
|
||||
t.Fatalf("%d jobs", len(jobs))
|
||||
}
|
||||
info, ok := conga.Describe(jobs[0])
|
||||
if !ok || info.Kind != classes.RebuildKind || info.MaxAttempts != 3 {
|
||||
t.Fatalf("job = %+v %v", info, ok)
|
||||
}
|
||||
}
|
||||
|
||||
59
console/rebuild.go
Normal file
59
console/rebuild.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
)
|
||||
|
||||
// Rebuild is sitemap:rebuild [--queue]: it rebuilds the sitemap files now
|
||||
// (classes.Rebuild), or with --queue dispatches the rebuild job for a
|
||||
// worker. The scheduler runs it every night at 03:00.
|
||||
func Rebuild(app *backpack.App) bonfire.Command {
|
||||
return bonfire.Command{
|
||||
Name: "sitemap:rebuild",
|
||||
Description: "Rebuild the sitemap files from the content types and the additional addresses",
|
||||
Long: `Reads the published records of every content type and the additional
|
||||
addresses, writes them into the sitemap's address table and numbers the
|
||||
files: existing addresses keep their files, new ones are appended, and only a
|
||||
changed file size renumbers. It runs in this process and ends with
|
||||
"Rebuilt the sitemaps: N addresses in N files (N added, N changed, N
|
||||
removed)."
|
||||
|
||||
--queue dispatches the rebuild job instead, for a worker to run. The
|
||||
scheduler runs this command every night at 03:00; record changes and a save
|
||||
of the sitemap settings queue a rebuild too.`,
|
||||
Flags: []bonfire.Flag{
|
||||
{Name: "queue", Description: "Dispatch the rebuild job for a worker instead of rebuilding here", Bare: true},
|
||||
},
|
||||
Examples: []bonfire.Example{
|
||||
{Command: "sitemap:rebuild", Description: "Rebuild the sitemap files now"},
|
||||
{Command: "sitemap:rebuild --queue", Description: "Queue a rebuild for the worker"},
|
||||
},
|
||||
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
|
||||
_, done, err := lookupDB(ctx, app)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer done()
|
||||
if flagOn(in, "queue") {
|
||||
id, err := classes.DispatchRebuild(ctx, app)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out.Success(fmt.Sprintf("Queued the sitemap rebuild (job %d).", id))
|
||||
return nil
|
||||
}
|
||||
res, err := classes.Rebuild(ctx, app)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out.Success(fmt.Sprintf("Rebuilt the sitemaps: %d addresses in %d files (%d added, %d changed, %d removed).",
|
||||
res.Listed, res.Files, len(res.Added), len(res.Changed), len(res.Removed)))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
6
jobs.go
6
jobs.go
@@ -15,8 +15,12 @@ func (p *Plugin) Jobs() []pact.Job {
|
||||
}
|
||||
}
|
||||
|
||||
// rebuild runs one rebuild of the slot table.
|
||||
// rebuild runs one rebuild of the slot table. It ends the debounce window
|
||||
// first, so record events during the rebuild queue the next one.
|
||||
func (p *Plugin) rebuild(ctx context.Context, _ classes.RebuildArgs) error {
|
||||
if err := classes.ClearPending(ctx, p.app); err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := classes.Rebuild(ctx, p.app)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
27
listeners.go
Normal file
27
listeners.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package sitemap
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
// listen subscribes to the framework's record events (D-92): a saved
|
||||
// record of a content type moves the lastmod of its addresses when the
|
||||
// save changed something real, a deleted one leaves the files, and both
|
||||
// queue a debounced rebuild (classes.RecordSaved, classes.RecordDeleted).
|
||||
// Listener errors are logged by the bus and never fail the write that
|
||||
// fired them.
|
||||
func (p *Plugin) listen(app *backpack.App) {
|
||||
if app == nil || app.Events == nil {
|
||||
return
|
||||
}
|
||||
app.Events.Listen("golem15.sitemap", func(ctx context.Context, ev *pact.RecordSaved) error {
|
||||
return classes.RecordSaved(ctx, p.app, ev)
|
||||
})
|
||||
app.Events.Listen("golem15.sitemap", func(ctx context.Context, ev *pact.RecordDeleted) error {
|
||||
return classes.RecordDeleted(ctx, p.app, ev)
|
||||
})
|
||||
}
|
||||
11
plugin.go
11
plugin.go
@@ -51,18 +51,23 @@ func (p *Plugin) Register(app *backpack.App) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Boot keeps the booted application for the routes, jobs and commands.
|
||||
// Boot keeps the booted application for the routes, jobs and commands and
|
||||
// subscribes to the record events.
|
||||
func (p *Plugin) Boot(app *backpack.App) error {
|
||||
p.app = app
|
||||
p.listen(app)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ConfigFS ships config/config.yaml: the default priority tier rules.
|
||||
// ConfigFS ships config/config.yaml: lastmod_ignore and
|
||||
// rebuild_delay_seconds.
|
||||
func (p *Plugin) ConfigFS() fs.FS { return configFS }
|
||||
|
||||
// Commands registers sitemap:import and sitemap:import-winter.
|
||||
// Commands registers sitemap:rebuild, sitemap:import and
|
||||
// sitemap:import-winter.
|
||||
func (p *Plugin) Commands() []bonfire.Command {
|
||||
return []bonfire.Command{
|
||||
console.Rebuild(p.app),
|
||||
console.Import(p.app),
|
||||
console.ImportWinter(p.app),
|
||||
}
|
||||
|
||||
11
schedule.go
Normal file
11
schedule.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package sitemap
|
||||
|
||||
import "git.golem15.com/golem15/summercms/modules/pact"
|
||||
|
||||
// Schedule runs sitemap:rebuild every night at 03:00 (app timezone), so
|
||||
// the files follow content that changed without a record event.
|
||||
func (p *Plugin) Schedule() []pact.ScheduledCommand {
|
||||
return []pact.ScheduledCommand{{Command: "sitemap:rebuild", Cadence: pact.DailyAt(3, 0)}}
|
||||
}
|
||||
|
||||
var _ pact.HasSchedule = (*Plugin)(nil)
|
||||
@@ -9,8 +9,10 @@ import (
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||
"git.golem15.com/golem15/sm-sitemap-plugin/console"
|
||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||
"git.golem15.com/golem15/sm-sitemap-plugin/updates"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
@@ -402,3 +404,219 @@ func TestMigrateDefinitions(t *testing.T) {
|
||||
t.Fatalf("the rollback left %d copied columns", columns)
|
||||
}
|
||||
}
|
||||
|
||||
// fileNos lists the file numbers of the listed rows of typ in record order.
|
||||
func (e *sitemapEnv) fileNos(t *testing.T, typ string) []int {
|
||||
t.Helper()
|
||||
var out []int
|
||||
if err := e.gdb.Raw(`SELECT file_no FROM golem15_sitemap_urls WHERE type_key = ? AND excluded_reason = '' ORDER BY record_id::int, locale`, typ).Scan(&out).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func intsEq(a []int, b ...int) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// TestStableNumbering pins D-30's numbering invariant over real rebuilds:
|
||||
// 5 addresses at size 2 fill files 1,1,2,2,3; a deleted record leaves a
|
||||
// hole in file 1 and files 2 and 3 keep their addresses; two new records go
|
||||
// to file 3, then a new file 4; only a file size change renumbers.
|
||||
func TestStableNumbering(t *testing.T) {
|
||||
e := bootIndex(t)
|
||||
e.setFileSize(t, 2)
|
||||
base := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||
for i := 1; i <= 5; i++ {
|
||||
contentStore.put(pageType, page1(i, string(rune('a'+i-1)), base))
|
||||
}
|
||||
e.rebuild(t)
|
||||
if got := e.fileNos(t, pageType); !intsEq(got, 1, 1, 2, 2, 3) {
|
||||
t.Fatalf("first build: %v", got)
|
||||
}
|
||||
file2 := e.get(t, "/_sitemap/files/sitemap-pages-2.xml").Body.String()
|
||||
|
||||
contentStore.remove(pageType, 2)
|
||||
e.rebuild(t)
|
||||
if got := e.fileNos(t, pageType); !intsEq(got, 1, 2, 2, 3) {
|
||||
t.Fatalf("after a delete: %v", got)
|
||||
}
|
||||
if got := locs(e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String()); len(got) != 1 || got[0] != "https://api.example.test/pages/a" {
|
||||
t.Fatalf("file 1 after the delete: %v", got)
|
||||
}
|
||||
if again := e.get(t, "/_sitemap/files/sitemap-pages-2.xml").Body.String(); again != file2 {
|
||||
t.Fatalf("file 2 changed after a delete in file 1:\n%s\n%s", file2, again)
|
||||
}
|
||||
var reason string
|
||||
e.gdb.Raw(`SELECT excluded_reason FROM golem15_sitemap_urls WHERE type_key = ? AND record_id = '2'`, pageType).Scan(&reason)
|
||||
if reason != "deleted" {
|
||||
t.Fatalf("the deleted record's row has reason %q", reason)
|
||||
}
|
||||
|
||||
contentStore.put(pageType, page1(6, "f", base))
|
||||
contentStore.put(pageType, page1(7, "g", base))
|
||||
e.rebuild(t)
|
||||
if got := e.fileNos(t, pageType); !intsEq(got, 1, 2, 2, 3, 3, 4) {
|
||||
t.Fatalf("after two appends: %v", got)
|
||||
}
|
||||
index := locs(e.get(t, "/sitemap.xml").Body.String())
|
||||
if len(index) != 4 || index[3] != "https://api.example.test/sitemap-pages-4.xml" {
|
||||
t.Fatalf("index after appends: %v", index)
|
||||
}
|
||||
|
||||
e.setFileSize(t, 3)
|
||||
e.rebuild(t)
|
||||
if got := e.fileNos(t, pageType); !intsEq(got, 1, 1, 1, 2, 2, 2) {
|
||||
t.Fatalf("after a file size change: %v", got)
|
||||
}
|
||||
if index := locs(e.get(t, "/sitemap.xml").Body.String()); len(index) != 2 {
|
||||
t.Fatalf("index after renumbering: %v", index)
|
||||
}
|
||||
}
|
||||
|
||||
// lastmodOf reads the lastmod of one row.
|
||||
func (e *sitemapEnv) lastmodOf(t *testing.T, typ, id, locale string) time.Time {
|
||||
t.Helper()
|
||||
var mod *time.Time
|
||||
if err := e.gdb.Raw(`SELECT lastmod FROM golem15_sitemap_urls WHERE type_key = ? AND record_id = ? AND locale = ?`, typ, id, locale).Scan(&mod).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mod == nil {
|
||||
t.Fatalf("%s %s %s has no lastmod", typ, id, locale)
|
||||
}
|
||||
return mod.UTC()
|
||||
}
|
||||
|
||||
// saved fires a RecordSaved of a fake page.
|
||||
func (e *sitemapEnv) saved(t *testing.T, id string, changes ...pact.RecordChange) {
|
||||
t.Helper()
|
||||
if err := e.app.Events.Fire(context.Background(), &pact.RecordSaved{Model: pageModel, ID: id, Changes: changes}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLastmod pins event-driven lastmod (D-30, RESEARCH Pitfall 4): a save
|
||||
// whose changes touch a real attribute moves the lastmod of that record's
|
||||
// rows (only the changed locale's row for a translated change); a no-op
|
||||
// save or one that changes only ignored attributes does not; a rebuild
|
||||
// never moves lastmod, even when the record's own LastMod moved; a deleted
|
||||
// record leaves the files at once.
|
||||
func TestLastmod(t *testing.T) {
|
||||
e := bootIndex(t)
|
||||
base := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||
contentStore.put(pageType, page1(1, "a", base))
|
||||
contentStore.put(pageType, fakeRecord{ID: 2, Published: true, LastMod: base, Locales: []pact.ContentLocale{
|
||||
{Locale: "en", URL: "/pages/b", Title: "B"},
|
||||
{Locale: "pl", URL: "/pl/strony/b", Title: "B pl"},
|
||||
}})
|
||||
e.rebuild(t)
|
||||
if got := e.lastmodOf(t, pageType, "1", "en"); !got.Equal(base) {
|
||||
t.Fatalf("first lastmod = %v, want the record's %v", got, base)
|
||||
}
|
||||
|
||||
e.saved(t, "1")
|
||||
e.saved(t, "1", pact.RecordChange{Attribute: "updated_at"}, pact.RecordChange{Attribute: "views", Old: 1, New: 2})
|
||||
if got := e.lastmodOf(t, pageType, "1", "en"); !got.Equal(base) {
|
||||
t.Fatalf("a no-op or ignored save moved lastmod to %v", got)
|
||||
}
|
||||
|
||||
before := time.Now().Add(-time.Second)
|
||||
e.saved(t, "1", pact.RecordChange{Attribute: "title", Old: "A", New: "A2"}, pact.RecordChange{Attribute: "updated_at"})
|
||||
if got := e.lastmodOf(t, pageType, "1", "en"); got.Before(before) {
|
||||
t.Fatalf("a title change left lastmod at %v", got)
|
||||
}
|
||||
|
||||
e.saved(t, "2", pact.RecordChange{Attribute: "title", Locale: "pl", Old: "B pl", New: "B pl 2"})
|
||||
if en, pl := e.lastmodOf(t, pageType, "2", "en"), e.lastmodOf(t, pageType, "2", "pl"); !en.Equal(base) || pl.Before(before) {
|
||||
t.Fatalf("a pl change: en %v, pl %v", en, pl)
|
||||
}
|
||||
|
||||
moved := e.lastmodOf(t, pageType, "1", "en")
|
||||
later := page1(1, "a", base.Add(48*time.Hour))
|
||||
contentStore.put(pageType, later)
|
||||
e.rebuild(t)
|
||||
if got := e.lastmodOf(t, pageType, "1", "en"); !got.Equal(moved) {
|
||||
t.Fatalf("a rebuild moved lastmod from %v to %v", moved, got)
|
||||
}
|
||||
|
||||
if err := e.app.Events.Fire(context.Background(), &pact.RecordDeleted{Model: pageModel, ID: "1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := locs(e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String()); strings.Contains(strings.Join(got, " "), "/pages/a") {
|
||||
t.Fatalf("a deleted record is still listed: %v", got)
|
||||
}
|
||||
// A record of a model no content type declares is ignored.
|
||||
if err := e.app.Events.Fire(context.Background(), &pact.RecordSaved{Model: "other_model", ID: "2", Changes: []pact.RecordChange{{Attribute: "title"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDebouncedRebuild pins P33-12: record events within the delay queue
|
||||
// exactly one rebuild job, scheduled after golem15.sitemap.rebuild_delay_seconds;
|
||||
// once the job ran, the next event queues another; a no-op save queues none.
|
||||
func TestDebouncedRebuild(t *testing.T) {
|
||||
e := bootIndex(t)
|
||||
contentStore.put(pageType, page1(1, "a", time.Now()))
|
||||
e.saved(t, "1")
|
||||
if n := e.riverJobs(t, classes.RebuildKind); n != 0 {
|
||||
t.Fatalf("a no-op save queued %d rebuilds", n)
|
||||
}
|
||||
start := time.Now()
|
||||
for range 3 {
|
||||
e.saved(t, "1", pact.RecordChange{Attribute: "title"})
|
||||
}
|
||||
if n := e.riverJobs(t, classes.RebuildKind); n != 1 {
|
||||
t.Fatalf("three saves queued %d rebuilds, want 1", n)
|
||||
}
|
||||
var at time.Time
|
||||
if err := e.gdb.Raw(`SELECT scheduled_at FROM river_job WHERE kind = ?`, classes.RebuildKind).Scan(&at).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d := at.Sub(start); d < 55*time.Second || d > 70*time.Second {
|
||||
t.Fatalf("the rebuild is scheduled %v after the first save, want about 60s", d)
|
||||
}
|
||||
e.rebuild(t)
|
||||
e.saved(t, "1", pact.RecordChange{Attribute: "title"})
|
||||
if n := e.riverJobs(t, classes.RebuildKind); n != 2 {
|
||||
t.Fatalf("a save after the rebuild: %d jobs, want 2", n)
|
||||
}
|
||||
if err := e.app.Events.Fire(context.Background(), &pact.RecordDeleted{Model: pageModel, ID: "1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := e.riverJobs(t, classes.RebuildKind); n != 2 {
|
||||
t.Fatalf("a delete within the delay queued another rebuild: %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRebuildCommand runs sitemap:rebuild through the console: without
|
||||
// --queue it rebuilds in the process and reports the counts, with --queue
|
||||
// it dispatches the rebuild job.
|
||||
func TestRebuildCommand(t *testing.T) {
|
||||
e := bootIndex(t)
|
||||
contentStore.put(pageType, page1(1, "a", time.Now()))
|
||||
run := func(args ...string) (int, string) {
|
||||
var buf strings.Builder
|
||||
root, err := bonfire.NewRootIO("summer", []bonfire.Command{console.Rebuild(e.app)}, strings.NewReader(""), &buf, &buf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return bonfire.Execute(context.Background(), root, args), buf.String()
|
||||
}
|
||||
if code, out := run("sitemap:rebuild"); code != 0 || !strings.Contains(out, "Rebuilt the sitemaps: 1 addresses in 1 files (1 added, 0 changed, 0 removed).") {
|
||||
t.Fatalf("sitemap:rebuild: %d\n%s", code, out)
|
||||
}
|
||||
if got := locs(e.get(t, "/sitemap.xml").Body.String()); len(got) != 1 {
|
||||
t.Fatalf("index after the command: %v", got)
|
||||
}
|
||||
if code, out := run("sitemap:rebuild", "--queue"); code != 0 || !strings.Contains(out, "Queued the sitemap rebuild") || e.riverJobs(t, classes.RebuildKind) != 1 {
|
||||
t.Fatalf("sitemap:rebuild --queue: %d\n%s", code, out)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user