Phase 5 part 5: check the live site after a merge

Merged Sites pages are checked on the live site until they answer with
their own words and title; removed ones until they're gone. The SEO loop,
the page, the signal's page and Sites → Publishing check (or Check now);
two hours without the page points at the deploy hook. Pages going live or
away go to IndexNow. Sites → Publishing lists what's waiting, open pull
requests and recent merges. Schema 24.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 14:28:42 -07:00
co-authored by Claude Opus 5.5
parent 062fcf2e59
commit e2a72d5ef9
18 changed files with 746 additions and 63 deletions
+211
View File
@@ -0,0 +1,211 @@
package sites
import (
"context"
"fmt"
"html"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"gopkg.in/yaml.v3"
"supermarket/internal/api/gitea"
"supermarket/internal/db"
"supermarket/internal/seo"
)
// GiveUpAfter is how long after merging a page that still isn't live is
// called a problem (the deploy hook, most likely).
const GiveUpAfter = 2 * time.Hour
// Address is the page's address on the live site.
func (p *SitePage) Address() string {
return strings.TrimRight(p.Site, "/") + p.Path
}
// Waiting says whether the live site hasn't caught up with the page yet:
// merged but not seen live, or removed but not seen gone.
func (p *SitePage) Waiting() bool {
return (p.Status == PageMerged && p.LiveAt.IsZero()) || (p.Status == PageRemoved && p.GoneAt.IsZero())
}
// Late says whether it's been waiting too long.
func (p *SitePage) Late(now time.Time) bool {
return p.Waiting() && !p.MergedAt.IsZero() && now.Sub(p.MergedAt) > GiveUpAfter && p.Status == PageMerged
}
// RefreshPR follows a page's open pull request (adding or removing it): a
// merge or a close changes its status. It says whether anything changed.
func RefreshPR(ctx context.Context, d *db.DB, g interface {
GetPull(context.Context, string, int64) (*gitea.Pull, error)
}, p *SitePage, now time.Time) (bool, error) {
_, full, err := gitea.ParseRepo(p.Repo)
if err != nil {
return false, nil
}
switch p.Status {
case PageRemoving:
pull, err := g.GetPull(ctx, full, p.RemovalPRNumber)
if err != nil {
return false, err
}
switch {
case pull.Merged:
p.Status, p.GoneAt, p.LiveNote = PageRemoved, time.Time{}, ""
p.MergedAt = now
if pull.MergedAt != nil {
p.MergedAt = *pull.MergedAt
}
case pull.State == "closed":
p.Status, p.RemovalPRNumber, p.RemovalPRURL = PageMerged, 0, ""
default:
return false, nil
}
case PagePR:
pull, err := g.GetPull(ctx, full, p.PRNumber)
if err != nil {
return false, err
}
switch {
case pull.Merged:
p.Status, p.MergedAt, p.LiveAt, p.LiveNote = PageMerged, now, time.Time{}, ""
if pull.MergedAt != nil {
p.MergedAt = *pull.MergedAt
}
case pull.State == "closed":
p.Status = PageClosed
default:
return false, nil
}
default:
return false, nil
}
return true, SavePage(d, p)
}
// CheckLive looks at the live site for a page that's waiting: a merged
// one must answer, with its title and its own words; a removed one must
// be gone (404 or 410, or sent elsewhere). It notes what it found.
func CheckLive(ctx context.Context, f *seo.Fetcher, p *SitePage, now time.Time) {
p.CheckedAt = now
lp, err := f.Page(ctx, p.Address())
if err != nil {
p.LiveNote = "Couldn't reach the site: " + err.Error()
return
}
if p.Status == PageRemoved {
moved := false
if u, err := url.Parse(lp.Final); err == nil && strings.TrimRight(u.Path, "/") != strings.TrimRight(p.Path, "/") {
moved = true
}
switch {
case lp.Status == http.StatusNotFound || lp.Status == http.StatusGone:
p.GoneAt, p.LiveNote = now, fmt.Sprintf("Gone from the site (it answers %d).", lp.Status)
case moved:
p.GoneAt, p.LiveNote = now, "Gone from the site: its address now leads to "+lp.Final+"."
default:
p.LiveNote = fmt.Sprintf("Still on the site (it answers %d).", lp.Status)
}
return
}
if lp.Status != http.StatusOK {
p.LiveNote = fmt.Sprintf("Not on the site yet (it answers %d).", lp.Status)
return
}
titleOK := p.Title == "" || strings.Contains(norm(lp.Title), norm(p.Title))
phrase := Phrase(p.Sections)
textOK := phrase == "" || strings.Contains(norm(lp.Text), norm(phrase))
switch {
case titleOK && textOK:
p.LiveAt, p.LiveNote = now, "Live: the title and the words match."
case textOK:
p.LiveAt, p.LiveNote = now, fmt.Sprintf("Live, but its title shows as %q.", lp.Title)
case titleOK:
p.LiveNote = fmt.Sprintf("The page is there with its title, but not this version's words yet (looking for %q).", phrase)
default:
p.LiveNote = fmt.Sprintf("Something else is at this address (its title is %q).", lp.Title)
}
}
var (
mdLinkText = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
mdMarks = regexp.MustCompile("[*_`#>]+")
spaces = regexp.MustCompile(`\s+`)
)
// Phrase is words from the page that should show on the live site: the
// first heading of its first section that has one, without Markdown.
func Phrase(sectionsYAML string) string {
var doc yaml.Node
if yaml.Unmarshal([]byte(sectionsYAML), &doc) != nil || len(doc.Content) == 0 || doc.Content[0].Kind != yaml.SequenceNode {
return ""
}
for _, sec := range doc.Content[0].Content {
for _, key := range []string{"title", "headline", "text", "body"} {
if v := mapValue(sec, key); v != nil && v.Kind == yaml.ScalarNode && strings.TrimSpace(v.Value) != "" {
s := mdLinkText.ReplaceAllString(v.Value, "$1")
s = strings.TrimSpace(spaces.ReplaceAllString(mdMarks.ReplaceAllString(s, ""), " "))
if r := []rune(s); len(r) > 80 {
s = string(r[:80])
if i := strings.LastIndex(s, " "); i > 20 {
s = s[:i]
}
}
return s
}
}
}
return ""
}
func norm(s string) string {
s = html.UnescapeString(s)
s = strings.NewReplacer("’", "'", "‘", "'", "“", `"`, "”", `"`, "–", "-", "—", "-", " ", " ").Replace(s)
return strings.ToLower(strings.TrimSpace(spaces.ReplaceAllString(s, " ")))
}
// Refresh follows every page's pull request and checks the live site for
// pages waiting on it. Pages are checked at most every few minutes.
func Refresh(ctx context.Context, d *db.DB, g interface {
GetPull(context.Context, string, int64) (*gitea.Pull, error)
}, f *seo.Fetcher, now time.Time) error {
ps, err := PagesIn(d, PagePR, PageRemoving, PageMerged, PageRemoved)
if err != nil {
return err
}
for i := range ps {
p := &ps[i]
if g != nil {
if _, err := RefreshPR(ctx, d, g, p, now); err != nil {
continue
}
}
if !p.Waiting() || now.Sub(p.CheckedAt) < 4*time.Minute {
continue
}
CheckLive(ctx, f, p, now)
if err := SavePage(d, p); err != nil {
return err
}
}
return nil
}
// LiveAddresses are pages that went live, or went away, since a time: for
// telling search engines (IndexNow takes both).
func LiveAddresses(d *db.DB, site string, since time.Time) ([]string, error) {
ps, err := Pages(d, site)
if err != nil {
return nil, err
}
var out []string
for _, p := range ps {
if (!p.LiveAt.IsZero() && p.LiveAt.After(since)) || (!p.GoneAt.IsZero() && p.GoneAt.After(since)) {
out = append(out, p.Address())
}
}
return out, nil
}
+163
View File
@@ -0,0 +1,163 @@
package sites
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"
"supermarket/internal/api/gitea"
"supermarket/internal/db"
"supermarket/internal/seo"
)
func openDB(t *testing.T) *db.DB {
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
func TestPhrase(t *testing.T) {
for in, want := range map[string]string{
"- type: hero\n title: \"**One bill** for [your church](/c/)\"\n": "One bill for your church",
"- type: stats\n items: []\n- type: text\n headline: Why it works\n": "Why it works",
"- type: hero\n subhead: no title here\n": "",
"- type: hero\n title: " + strings.Repeat("word ", 30) + "\n": strings.TrimSpace(strings.Repeat("word ", 16)),
"not yaml: [": "",
} {
if got := Phrase(in); got != want {
t.Errorf("%q: %q, want %q", in, got, want)
}
}
}
func TestCheckLive(t *testing.T) {
var page string
status := 200
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/moved/" {
http.Redirect(w, r, "/elsewhere/", http.StatusMovedPermanently)
return
}
w.WriteHeader(status)
fmt.Fprint(w, page)
}))
defer srv.Close()
f := seo.NewFetcher("test")
now := time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)
p := &SitePage{Site: srv.URL + "/", Path: "/for-churches/", Title: "For churches", Status: PageMerged,
Sections: "- type: hero\n title: Run your church on one bill\n", MergedAt: now.Add(-time.Hour)}
status = 404
CheckLive(context.Background(), f, p, now)
if !p.LiveAt.IsZero() || p.LiveNote != "Not on the site yet (it answers 404)." || !p.CheckedAt.Equal(now) || !p.Waiting() || p.Late(now) {
t.Errorf("404: %+v", p)
}
status = 200
page = `<html><head><title>Old page · Us</title></head><body><h1>Something else</h1></body></html>`
CheckLive(context.Background(), f, p, now)
if !p.LiveAt.IsZero() || !strings.Contains(p.LiveNote, `Something else is at this address (its title is "Old page · Us")`) {
t.Errorf("other page: %s", p.LiveNote)
}
page = `<html><head><title>For churches · Us</title></head><body><h1>For churches</h1><p>An older version.</p></body></html>`
CheckLive(context.Background(), f, p, now)
if !p.LiveAt.IsZero() || !strings.Contains(p.LiveNote, "not this version's words yet") {
t.Errorf("old version: %s", p.LiveNote)
}
if !p.Late(now.Add(2 * time.Hour)) {
t.Error("not late after three hours")
}
page = `<html><head><title>Churches</title></head><body><h2>Run your church on&nbsp;one bill</h2></body></html>`
CheckLive(context.Background(), f, p, now)
if !p.LiveAt.Equal(now) || p.LiveNote != `Live, but its title shows as "Churches".` || p.Waiting() {
t.Errorf("live, other title: %+v", p)
}
p.LiveAt = time.Time{}
page = `<html><head><title>For churches · Us</title></head><body><h2>Run your church on one bill</h2></body></html>`
CheckLive(context.Background(), f, p, now)
if !p.LiveAt.Equal(now) || p.LiveNote != "Live: the title and the words match." {
t.Errorf("live: %+v", p)
}
// Removed pages must be gone.
p.Status = PageRemoved
CheckLive(context.Background(), f, p, now)
if !p.GoneAt.IsZero() || p.LiveNote != "Still on the site (it answers 200)." {
t.Errorf("still there: %s", p.LiveNote)
}
status = 410
CheckLive(context.Background(), f, p, now)
if !p.GoneAt.Equal(now) || p.Waiting() {
t.Errorf("gone: %+v", p)
}
p.GoneAt, p.Path, status = time.Time{}, "/moved/", 200
CheckLive(context.Background(), f, p, now)
if p.GoneAt.IsZero() || !strings.Contains(p.LiveNote, "/elsewhere/") {
t.Errorf("redirected: %s", p.LiveNote)
}
}
type fakePulls map[int64]*gitea.Pull
func (f fakePulls) GetPull(_ context.Context, full string, n int64) (*gitea.Pull, error) {
if full != "Us/site" {
return nil, fmt.Errorf("repo %s", full)
}
return f[n], nil
}
func TestRefresh(t *testing.T) {
d := openDB(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `<html><head><title>A</title></head><body><h2>Hello there</h2></body></html>`)
}))
defer srv.Close()
at := time.Date(2026, 11, 22, 9, 0, 0, 0, time.UTC)
mk := func(path, status string, pr int64) *SitePage {
p := &SitePage{Site: srv.URL + "/", Repo: "Us/site", Kind: "landing", Path: path, Title: "A", Status: status, PRNumber: pr,
Sections: "- type: hero\n title: Hello there\n"}
if err := SavePage(d, p); err != nil {
t.Fatal(err)
}
return p
}
open := mk("/open/", PagePR, 1)
merging := mk("/merging/", PagePR, 2)
closing := mk("/closing/", PagePR, 3)
draft := mk("/draft/", PageDraft, 0)
g := fakePulls{1: {State: "open"}, 2: {State: "closed", Merged: true, MergedAt: &at}, 3: {State: "closed"}}
now := at.Add(time.Hour)
if err := Refresh(context.Background(), d, g, seo.NewFetcher("test"), now); err != nil {
t.Fatal(err)
}
for _, c := range []struct {
p *SitePage
status string
live bool
}{{open, PagePR, false}, {merging, PageMerged, true}, {closing, PageClosed, false}, {draft, PageDraft, false}} {
got, _ := GetPage(d, c.p.ID)
if got.Status != c.status || got.LiveAt.IsZero() == c.live {
t.Errorf("%s: %s live=%v", c.p.Path, got.Status, !got.LiveAt.IsZero())
}
}
got, _ := GetPage(d, merging.ID)
if !got.MergedAt.Equal(at) || got.LiveNote != "Live: the title and the words match." {
t.Errorf("merged: %+v", got)
}
// Live and gone addresses are for IndexNow; seo picks them up too.
addrs, _ := LiveAddresses(d, srv.URL+"/", at)
if len(addrs) != 1 || addrs[0] != srv.URL+"/merging/" {
t.Errorf("addresses: %v", addrs)
}
newly, err := seo.NewlyLive(d, srv.URL+"/", now)
if err != nil || len(newly) != 1 || newly[0] != srv.URL+"/merging/" {
t.Errorf("newly live: %v %v", newly, err)
}
}
+28 -13
View File
@@ -93,6 +93,11 @@ type SitePage struct {
RemovalBranch string
RemovalPRNumber int64
RemovalPRURL string
LiveAt time.Time // seen on the live site after merging
GoneAt time.Time // seen gone after its removal was merged
CheckedAt time.Time // the live site was last checked
LiveNote string // what that check found
}
// Live says whether the page is on the published site.
@@ -114,7 +119,7 @@ func (p *SitePage) Editable() bool {
const pageCols = `id, site, repo, kind, source, notes, path, title, description, sections, needs, warnings, claims,
status, branch, file, pr_number, pr_url, note, error, created_at, updated_at, merged_at,
removal_branch, removal_pr_number, removal_pr_url`
removal_branch, removal_pr_number, removal_pr_url, live_at, gone_at, checked_at, live_note`
func scanPages(rows *sql.Rows) ([]SitePage, error) {
defer rows.Close()
@@ -122,10 +127,11 @@ func scanPages(rows *sql.Rows) ([]SitePage, error) {
for rows.Next() {
var p SitePage
var src, needs, warns, claims, created, updated string
var merged sql.NullString
var merged, live, gone, checked sql.NullString
if err := rows.Scan(&p.ID, &p.Site, &p.Repo, &p.Kind, &src, &p.Notes, &p.Path, &p.Title, &p.Description, &p.Sections,
&needs, &warns, &claims, &p.Status, &p.Branch, &p.File, &p.PRNumber, &p.PRURL, &p.Note, &p.Error,
&created, &updated, &merged, &p.RemovalBranch, &p.RemovalPRNumber, &p.RemovalPRURL); err != nil {
&created, &updated, &merged, &p.RemovalBranch, &p.RemovalPRNumber, &p.RemovalPRURL,
&live, &gone, &checked, &p.LiveNote); err != nil {
return nil, err
}
_ = json.Unmarshal([]byte(src), &p.Source)
@@ -134,8 +140,13 @@ func scanPages(rows *sql.Rows) ([]SitePage, error) {
_ = json.Unmarshal([]byte(claims), &p.Claims)
p.CreatedAt, _ = time.Parse(time.RFC3339, created)
p.UpdatedAt, _ = time.Parse(time.RFC3339, updated)
if merged.Valid {
p.MergedAt, _ = time.Parse(time.RFC3339, merged.String)
for _, t := range []struct {
v sql.NullString
to *time.Time
}{{merged, &p.MergedAt}, {live, &p.LiveAt}, {gone, &p.GoneAt}, {checked, &p.CheckedAt}} {
if t.v.Valid {
*t.to, _ = time.Parse(time.RFC3339, t.v.String)
}
}
out = append(out, p)
}
@@ -226,10 +237,13 @@ func PagesIn(d *db.DB, statuses ...string) ([]SitePage, error) {
func SavePage(d *db.DB, p *SitePage) error {
now := time.Now().UTC()
p.UpdatedAt = now
var merged any
if !p.MergedAt.IsZero() {
merged = p.MergedAt.UTC().Format(time.RFC3339)
ts := func(t time.Time) any {
if t.IsZero() {
return nil
}
return t.UTC().Format(time.RFC3339)
}
merged := ts(p.MergedAt)
src, _ := json.Marshal(p.Source)
if p.ID == 0 {
if p.CreatedAt.IsZero() {
@@ -240,12 +254,12 @@ func SavePage(d *db.DB, p *SitePage) error {
}
res, err := d.Exec(`INSERT INTO site_pages (site, repo, kind, source, notes, path, title, description, sections, needs, warnings,
claims, status, branch, file, pr_number, pr_url, note, error, created_at, updated_at, merged_at,
removal_branch, removal_pr_number, removal_pr_url)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
removal_branch, removal_pr_number, removal_pr_url, live_at, gone_at, checked_at, live_note)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
p.Site, p.Repo, p.Kind, string(src), p.Notes, p.Path, p.Title, p.Description, p.Sections, jsonText(p.Needs), jsonText(p.Warnings),
jsonText(p.Claims), p.Status, p.Branch, p.File, p.PRNumber, p.PRURL, p.Note, p.Error,
p.CreatedAt.UTC().Format(time.RFC3339), now.Format(time.RFC3339), merged,
p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL)
p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL, ts(p.LiveAt), ts(p.GoneAt), ts(p.CheckedAt), p.LiveNote)
if err != nil {
return err
}
@@ -254,10 +268,11 @@ func SavePage(d *db.DB, p *SitePage) error {
}
res, err := d.Exec(`UPDATE site_pages SET site = ?, repo = ?, kind = ?, source = ?, notes = ?, path = ?, title = ?, description = ?,
sections = ?, needs = ?, warnings = ?, claims = ?, status = ?, branch = ?, file = ?, pr_number = ?, pr_url = ?, note = ?, error = ?,
updated_at = ?, merged_at = ?, removal_branch = ?, removal_pr_number = ?, removal_pr_url = ? WHERE id = ?`,
updated_at = ?, merged_at = ?, removal_branch = ?, removal_pr_number = ?, removal_pr_url = ?,
live_at = ?, gone_at = ?, checked_at = ?, live_note = ? WHERE id = ?`,
p.Site, p.Repo, p.Kind, string(src), p.Notes, p.Path, p.Title, p.Description, p.Sections, jsonText(p.Needs), jsonText(p.Warnings),
jsonText(p.Claims), p.Status, p.Branch, p.File, p.PRNumber, p.PRURL, p.Note, p.Error, now.Format(time.RFC3339), merged,
p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL, p.ID)
p.RemovalBranch, p.RemovalPRNumber, p.RemovalPRURL, ts(p.LiveAt), ts(p.GoneAt), ts(p.CheckedAt), p.LiveNote, p.ID)
if err != nil {
return err
}