Phase 3 part 7: Bing, IndexNow and search engine setup

SEO → Search engines: a pull request that adds the IndexNow key file, a
robots.txt naming the sitemap, and turns the sitemap on when the Hugo
config disables it (checked with a build); IndexNow submissions of pages
that go live through Changes or Briefs once the key file is served; the
sitemaps Search Console has; and, with an API key, Bing's traffic,
searches and crawl issues. NewlyLive no longer queries while a result
set holds the database's only connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 08:45:13 -07:00
co-authored by Claude Opus 5.5
parent bf933971dd
commit 2302fb0436
18 changed files with 1061 additions and 4 deletions
+267
View File
@@ -0,0 +1,267 @@
package seo
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"supermarket/internal/db"
"supermarket/internal/hugorepo"
)
// --- IndexNow ---
// IndexNowURL is where pings go; it shares them with Bing, Yandex, Seznam,
// Naver and the other engines that take part (Google doesn't). Tests
// replace it.
var IndexNowURL = "https://api.indexnow.org/indexnow"
const indexNowKeyKey = "seo:indexnow-key"
// IndexNowKey is the site's IndexNow key, made the first time. It isn't a
// secret: it's published in a file on the site.
func IndexNowKey(d *db.DB) (string, error) {
var k string
if _, err := d.GetJSON(indexNowKeyKey, &k); err != nil {
return "", err
}
if k != "" {
return k, nil
}
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
k = hex.EncodeToString(b)
return k, d.PutJSON(indexNowKeyKey, k)
}
// KeyFileURL is where the key file must be on a site.
func KeyFileURL(site, key string) string {
return strings.TrimRight(site, "/") + "/" + key + ".txt"
}
// KeyLive reports whether the site serves its IndexNow key file.
func KeyLive(ctx context.Context, f *Fetcher, site, key string) bool {
r, err := f.get(ctx, KeyFileURL(site, key), http.MethodGet, 4096)
return err == nil && r.status == 200 && strings.TrimSpace(string(r.body)) == key
}
// Ping is one IndexNow submission.
type Ping struct {
At time.Time `json:"at"`
URLs []string `json:"urls"`
Status int `json:"status"`
Error string `json:"error,omitempty"`
}
func pingsKey(site string) string { return "seo:indexnow-pings:" + site }
// Pings are a site's recent submissions, newest first.
func Pings(d *db.DB, site string) []Ping {
var out []Ping
_, _ = d.GetJSON(pingsKey(site), &out)
return out
}
// pinged reports whether a page was submitted already.
func pinged(d *db.DB, site, page string) bool {
for _, p := range Pings(d, site) {
for _, u := range p.URLs {
if u == page && p.Error == "" {
return true
}
}
}
return false
}
// SubmitIndexNow tells the IndexNow engines that pages changed, and keeps
// the submission.
func SubmitIndexNow(ctx context.Context, d *db.DB, site, key string, pages []string, now time.Time) (*Ping, error) {
u, err := url.Parse(site)
if err != nil || u.Host == "" {
return nil, fmt.Errorf("%q isn't a website address", site)
}
body, _ := json.Marshal(map[string]any{"host": u.Host, "key": key, "keyLocation": KeyFileURL(site, key), "urlList": pages})
p := &Ping{At: now, URLs: pages}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, IndexNowURL, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
res, err := http.DefaultClient.Do(req)
if err != nil {
p.Error = err.Error()
} else {
p.Status = res.StatusCode
msg, _ := io.ReadAll(io.LimitReader(res.Body, 2048))
res.Body.Close()
// 200: accepted; 202: accepted, the key is being checked.
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {
p.Error = fmt.Sprintf("IndexNow said HTTP %d %s", res.StatusCode, strings.TrimSpace(string(msg)))
}
}
list := append([]Ping{*p}, Pings(d, site)...)
if len(list) > 30 {
list = list[:30]
}
if perr := d.PutJSON(pingsKey(site), list); perr != nil {
return p, perr
}
if p.Error != "" {
return p, errors.New(p.Error)
}
return p, nil
}
// NewlyLive are the site's pages that went live in the last 14 days (from
// changes and briefs) and haven't been submitted to IndexNow yet.
func NewlyLive(d *db.DB, site string, now time.Time) ([]string, error) {
since := now.AddDate(0, 0, -14).UTC().Format(time.RFC3339)
rows, err := d.Query(`SELECT page FROM seo_changes WHERE site = ? AND status = 'live' AND live_at >= ?
UNION SELECT page FROM seo_briefs WHERE site = ? AND status = 'live' AND live_at >= ? AND page != ''`, site, since, site, since)
if err != nil {
return nil, err
}
// Read every row before looking anything else up: the database has one
// connection, which the open query holds.
var live []string
for rows.Next() {
var p string
if err := rows.Scan(&p); err != nil {
rows.Close()
return nil, err
}
live = append(live, p)
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
var out []string
for _, p := range live {
if !pinged(d, site, p) {
out = append(out, p)
}
}
return out, nil
}
// --- Setting the site up for search engines ---
// Setup is the "set the site up" pull request's state.
type Setup struct {
At time.Time `json:"at"`
PRNumber int64 `json:"pr_number"`
PRURL string `json:"pr_url"`
Done []string `json:"done"`
Note string `json:"note"`
Error string `json:"error,omitempty"`
}
func setupKey(site string) string { return "seo:setup:" + site }
// LastSetup is a site's last setup pull request, or nil.
func LastSetup(d *db.DB, site string) *Setup {
var s Setup
if ok, _ := d.GetJSON(setupKey(site), &s); !ok {
return nil
}
return &s
}
// SetupSite opens one pull request that gets the site ready for search
// engines: the IndexNow key file, a robots.txt naming the sitemap (unless
// the site has its own), and the sitemap turned back on if the Hugo config
// turns it off. A build checks the sitemap, robots.txt and key file come
// out.
func (ap *Applier) SetupSite(ctx context.Context, d *db.DB, site, key string, now time.Time) (*Setup, error) {
st := &Setup{At: now}
err := ap.setupSite(ctx, site, key, st)
if err != nil {
st.Error = err.Error()
}
if perr := d.PutJSON(setupKey(site), st); perr != nil && err == nil {
err = perr
}
return st, err
}
func (ap *Applier) setupSite(ctx context.Context, site, key string, st *Setup) error {
wc, full, branch, err := ap.workingCopy(ctx)
if err != nil {
return err
}
canBuild, note := buildCheck(ctx, wc)
work := "supermarket/search-engines"
if err := wc.NewBranch(ctx, work); err != nil {
return err
}
keyFile := "static/" + key + ".txt"
if !wc.Exists(keyFile) {
if err := wc.WriteFile(keyFile, key+"\n"); err != nil {
return err
}
st.Done = append(st.Done, "Adds the IndexNow key file ("+key+".txt), so Supermarket can tell Bing and other engines when a page changes.")
}
if !wc.Exists("static/robots.txt") && !wc.Exists("layouts/robots.txt") {
robots := "User-agent: *\nAllow: /\n\nSitemap: " + strings.TrimRight(site, "/") + "/sitemap.xml\n"
if err := wc.WriteFile("static/robots.txt", robots); err != nil {
return err
}
st.Done = append(st.Done, "Adds a robots.txt that lets every crawler in and names the sitemap.")
}
if changed, err := wc.EnableSitemap(); err != nil {
return err
} else if changed {
st.Done = append(st.Done, "Turns the sitemap back on: the Hugo config listed it under disableKinds.")
}
if len(st.Done) == 0 {
return errors.New("the site already has the key file and its own robots.txt, and its config doesn't turn the sitemap off")
}
if canBuild {
out, err := wc.Build(ctx)
if err != nil {
return fmt.Errorf("after the change, %w", err)
}
var missing []string
for _, f := range []string{"sitemap.xml", "robots.txt", key + ".txt"} {
if _, err := hugorepo.BuiltFile(out, f); err != nil {
missing = append(missing, f)
}
}
os.RemoveAll(out)
if len(missing) > 0 {
note = "The build doesn't produce " + strings.Join(missing, ", ") + ": the theme or config may turn it off in a way Supermarket can't change; check before merging."
} else {
note = "Checked with a build: the site now produces sitemap.xml, robots.txt and the key file."
}
}
subject := "SEO: set the site up for search engines"
if err := wc.CommitAndPush(ctx, work, subject); err != nil {
return err
}
var body strings.Builder
body.WriteString("Proposed by Supermarket, from the audit.\n\n")
for _, d := range st.Done {
body.WriteString("- " + d + "\n")
}
body.WriteString("\n" + note + "\n\nAfter merging, submit " + strings.TrimRight(site, "/") + "/sitemap.xml in Google Search Console and Bing Webmaster Tools.")
pr, err := ap.Gitea.OpenPull(ctx, full, work, branch, subject, body.String())
if err != nil {
return err
}
st.PRNumber, st.PRURL, st.Note = pr.Number, pr.HTMLURL, note
return nil
}
+113
View File
@@ -0,0 +1,113 @@
package seo
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"supermarket/internal/api/gitea"
"supermarket/internal/hugorepo"
"supermarket/internal/hugorepo/hugotest"
)
func TestIndexNow(t *testing.T) {
d := openDB(t)
key, err := IndexNowKey(d)
if err != nil || len(key) != 32 {
t.Fatalf("key: %q %v", key, err)
}
if again, _ := IndexNowKey(d); again != key {
t.Error("the key changed")
}
var got map[string]any
in := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewDecoder(r.Body).Decode(&got)
w.WriteHeader(http.StatusAccepted)
}))
defer in.Close()
IndexNowURL = in.URL
defer func() { IndexNowURL = "https://api.indexnow.org/indexnow" }()
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/"+key+".txt" {
fmt.Fprintln(w, key)
return
}
http.NotFound(w, r)
}))
defer site.Close()
f := NewFetcher("test")
if !KeyLive(context.Background(), f, site.URL, key) || KeyLive(context.Background(), f, site.URL, "other") {
t.Error("key check")
}
// A change went live: it's waiting to be submitted, then it isn't.
now := time.Now()
c := &Change{Site: site.URL + "/", Page: site.URL + "/pricing/", NewTitle: "x", CreatedAt: now}
insertChange(d, c)
d.Exec(`UPDATE seo_changes SET status = 'live', live_at = ? WHERE id = ?`, now.UTC().Format(time.RFC3339), c.ID)
pages, _ := NewlyLive(d, site.URL+"/", now)
if len(pages) != 1 {
t.Fatalf("newly live: %v", pages)
}
p, err := SubmitIndexNow(context.Background(), d, site.URL+"/", key, pages, now)
if err != nil || p.Status != 202 {
t.Fatalf("submit: %+v %v", p, err)
}
if got["key"] != key || got["keyLocation"] != site.URL+"/"+key+".txt" || !strings.HasPrefix(site.URL, "http://"+got["host"].(string)) {
t.Errorf("request: %+v", got)
}
if pages, _ := NewlyLive(d, site.URL+"/", now); len(pages) != 0 {
t.Errorf("submitted twice: %v", pages)
}
if len(Pings(d, site.URL+"/")) != 1 {
t.Error("the ping isn't kept")
}
}
func TestSetupSite(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
d := openDB(t)
clone := hugotest.Site(t)
var body map[string]string
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/o/site":
json.NewEncoder(w).Encode(map[string]any{"full_name": "o/site", "default_branch": "main", "clone_url": clone, "permissions": map[string]any{"push": true}})
case r.URL.Path == "/api/v1/repos/o/site/pulls":
json.NewDecoder(r.Body).Decode(&body)
json.NewEncoder(w).Encode(map[string]any{"number": 3, "html_url": "https://gitea.example/pr/3"})
}
}))
defer g.Close()
ap := &Applier{Gitea: gitea.New(g.URL, "tok"), Repo: "o/site", ReposDir: filepath.Join(t.TempDir(), "sites"), Author: "P <p@example.com>"}
st, err := ap.SetupSite(context.Background(), d, "https://site.example", "abc123", time.Now())
if err != nil {
t.Fatal(err)
}
if st.PRNumber != 3 || len(st.Done) != 3 || !strings.HasPrefix(st.Note, "Checked with a build") {
t.Fatalf("setup: %+v", st)
}
if !strings.Contains(body["body"], "Turns the sitemap back on") || !strings.Contains(body["body"], "https://site.example/sitemap.xml") {
t.Errorf("pull request: %s", body["body"])
}
repo := strings.TrimPrefix(clone, "file://")
for file, want := range map[string]string{
"static/abc123.txt": "abc123", "static/robots.txt": "Sitemap: https://site.example/sitemap.xml", "hugo.toml": "disableKinds = ['taxonomy', 'term', 'RSS']",
} {
out, err := exec.Command("git", "-C", repo, "show", "supermarket/search-engines:"+file).CombinedOutput()
if err != nil || !strings.Contains(string(out), want) {
t.Errorf("%s: %s %v", file, out, err)
}
}
if LastSetup(d, "https://site.example") == nil {
t.Error("the setup isn't kept")
}
}