Phase 8 part 3: lost links

Each known linking page (from Bing, Plausible or added by hand) is
opened once a week, at most 100 a day, to check it still links to the
site: kept, gone (the page no longer has the link), page gone (404, 410
or moved elsewhere) or pointing at a 404 (our page it links to is gone).
SEO → Links lists the lost ones with what happened, when last seen and
what the site brought; links can be added by hand (checked at once),
checked now, or forgotten. What to write next suggests a redirect for a
link to a 404, and asking for a lost link back when it brought visitors.
Links and What to write next now work for websites without Search
Console too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 08:43:30 -07:00
co-authored by Claude Opus 5.5
parent fc7dcf1f66
commit a1409d91ad
9 changed files with 539 additions and 7 deletions
+227
View File
@@ -0,0 +1,227 @@
package backlinks
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"supermarket/internal/db"
"supermarket/internal/seo"
)
// Whether a link is still there, as the last check found.
const (
StatusUnchecked = "unchecked"
StatusKept = "kept" // the page still links to the site
StatusGone = "gone" // the page is there, without the link
StatusPageGone = "page-gone" // the page answers 404 or 410, or moved elsewhere
StatusTarget404 = "target-404" // it links to a page of ours that's gone
)
// Checking politely: each link at most once a week, at most MaxPerDay
// pages a day in all.
const (
CheckEvery = 7 * 24 * time.Hour
MaxPerDay = 100
)
// Lost says whether a link was lost (or points nowhere).
func (l Link) Lost() bool {
return l.Status == StatusGone || l.Status == StatusPageGone || l.Status == StatusTarget404
}
// Fetcher reads a page of another site.
type Fetcher interface {
Page(ctx context.Context, u string) (*seo.LivePage, error)
}
func checkedKey(day string) string { return "backlinks:checked:" + day }
// CheckDue checks a website's links that are due (never checked, or not
// for a week), oldest first, within what's left of today's MaxPerDay; at
// most limit of them (0: no limit but the day's). It returns how many it
// checked.
func CheckDue(ctx context.Context, d *db.DB, f Fetcher, siteURL string, limit int, now time.Time) (int, error) {
day := now.Format(dayFormat)
var done int
_, _ = d.GetJSON(checkedKey(day), &done)
left := MaxPerDay - done
if limit > 0 && limit < left {
left = limit
}
if left <= 0 {
return 0, nil
}
rows, err := d.Query(`SELECT id FROM backlinks WHERE site = ? AND (checked_at IS NULL OR checked_at < ?)
ORDER BY coalesce(checked_at, ''), id LIMIT ?`, siteURL, now.Add(-CheckEvery).UTC().Format(time.RFC3339), left)
if err != nil {
return 0, err
}
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
rows.Close()
return 0, err
}
ids = append(ids, id)
}
rows.Close()
ours := map[string]int{} // our pages' answers, once per run
n := 0
for _, id := range ids {
if ctx.Err() != nil {
break
}
l, err := Get(d, id)
if err != nil {
return n, err
}
Check(ctx, f, siteURL, l, ours, now)
if err := save(d, l); err != nil {
return n, err
}
n++
}
return n, d.PutJSON(checkedKey(day), done+n)
}
// Check opens the linking page and says whether it still links to the
// site, and whether the page of ours it links to still answers.
func Check(ctx context.Context, f Fetcher, siteURL string, l *Link, ours map[string]int, now time.Time) {
l.CheckedAt = now
own := hostOf(siteURL)
lp, err := f.Page(ctx, l.Source)
if err != nil {
// Unreachable this time: not a verdict. Keep the last one.
l.Note = "Couldn't reach the page: " + err.Error()
if l.Status == "" {
l.Status = StatusUnchecked
}
return
}
switch {
case lp.Status == http.StatusNotFound || lp.Status == http.StatusGone:
l.Status, l.Note = StatusPageGone, fmt.Sprintf("The page answers %d.", lp.Status)
return
case lp.Status != http.StatusOK:
l.Note = fmt.Sprintf("The page answered %d; trying again next week.", lp.Status)
if l.Status == "" {
l.Status = StatusUnchecked
}
return
}
if moved(l.Source, lp.Final) {
l.Status, l.Note = StatusPageGone, "The page now leads to "+lp.Final+"."
return
}
found := ""
for _, link := range lp.Links {
if hostOf(link) == own {
found = link
if l.Target == "" || pathOf(link) == l.Target {
break
}
}
}
if found == "" {
l.Status, l.Note = StatusGone, "The page is there, but no longer links to the site."
return
}
if l.Target == "" {
l.Target = pathOf(found)
}
l.LastSeen = now.Format(dayFormat)
// The page of ours it links to: still there?
target := strings.TrimRight(siteURL, "/") + pathOf(found)
status, ok := ours[target]
if !ok {
if tp, err := f.Page(ctx, target); err == nil {
status = tp.Status
}
ours[target] = status
}
if status == http.StatusNotFound || status == http.StatusGone {
l.Status, l.Note = StatusTarget404, fmt.Sprintf("It links to %s, which answers %d: a redirect to where that page went keeps the link working.", pathOf(found), status)
return
}
l.Status, l.Note = StatusKept, "Still links to "+pathOf(found)+"."
}
// moved says whether a page's final address is a different page: another
// site, or another path (not just http to https, www or a slash).
func moved(from, to string) bool {
if to == "" {
return false
}
a, err1 := url.Parse(from)
b, err2 := url.Parse(to)
if err1 != nil || err2 != nil {
return false
}
return hostOf(from) != hostOf(to) || strings.TrimRight(a.Path, "/") != strings.TrimRight(b.Path, "/")
}
// Get reads one link.
func Get(d *db.DB, id int64) (*Link, error) {
var l Link
var checked string
err := d.QueryRow(`SELECT id, source_url, target, anchor, origin, first_seen, last_seen, status, coalesce(checked_at, ''), note
FROM backlinks WHERE id = ?`, id).Scan(&l.ID, &l.Source, &l.Target, &l.Anchor, &l.Origin, &l.FirstSeen, &l.LastSeen, &l.Status, &checked, &l.Note)
if err != nil {
return nil, err
}
l.CheckedAt, _ = time.Parse(time.RFC3339, checked)
return &l, nil
}
func save(d *db.DB, l *Link) error {
var checked any
if !l.CheckedAt.IsZero() {
checked = l.CheckedAt.UTC().Format(time.RFC3339)
}
_, err := d.Exec(`UPDATE backlinks SET target = ?, status = ?, note = ?, checked_at = ?, last_seen = max(last_seen, ?) WHERE id = ?`,
l.Target, l.Status, l.Note, checked, l.LastSeen, l.ID)
return err
}
// Add keeps a linking page the user knows of; it's checked like the rest.
func Add(d *db.DB, siteURL, source, target string, now time.Time) (*Link, error) {
source = strings.TrimSpace(source)
u, err := url.Parse(source)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return nil, errors.New("give the linking page's full address (https://…)")
}
if hostOf(source) == hostOf(siteURL) {
return nil, errors.New("that's a page of your own site: give the other site's page that links to it")
}
if target = strings.TrimSpace(target); target != "" {
target = pathOf(target)
}
day := now.Format(dayFormat)
if err := upsert(d, siteURL, source, target, "", OriginManual, day); err != nil {
return nil, err
}
var id int64
if err := d.QueryRow(`SELECT id FROM backlinks WHERE site = ? AND source_url = ? AND target = ?`, siteURL, strings.SplitN(source, "#", 2)[0], target).Scan(&id); err != nil {
return nil, err
}
return Get(d, id)
}
// CheckOne checks one link now (after it's added by hand), whatever the
// day's count.
func CheckOne(ctx context.Context, d *db.DB, f Fetcher, siteURL string, l *Link, now time.Time) error {
Check(ctx, f, siteURL, l, map[string]int{}, now)
return save(d, l)
}
// Remove forgets a link.
func Remove(d *db.DB, siteURL string, id int64) error {
_, err := d.Exec(`DELETE FROM backlinks WHERE id = ? AND site = ?`, id, siteURL)
return err
}
+89
View File
@@ -0,0 +1,89 @@
package backlinks
import (
"context"
"errors"
"testing"
"time"
"supermarket/internal/seo"
)
type fakeWeb map[string]*seo.LivePage
func (f fakeWeb) Page(_ context.Context, u string) (*seo.LivePage, error) {
if p, ok := f[u]; ok {
return p, nil
}
return nil, errors.New("no route")
}
func TestCheck(t *testing.T) {
d := openDB(t)
site := "https://example.com/"
now := time.Date(2026, 11, 24, 9, 0, 0, 0, time.UTC)
web := fakeWeb{
"https://kept.example/list": {Status: 200, Final: "https://kept.example/list", Links: []string{"https://www.example.com/freescout/"}},
"https://gone.example/list": {Status: 200, Final: "https://gone.example/list", Links: []string{"https://other.example/"}},
"https://dead.example/post": {Status: 404},
"https://moved.example/a": {Status: 200, Final: "https://moved.example/b"},
"https://old.example/x": {Status: 200, Final: "https://old.example/x", Links: []string{"https://example.com/old-page"}},
"https://example.com/freescout/": {Status: 200},
"https://example.com/old-page/": {Status: 404},
}
for _, src := range []string{"https://kept.example/list", "https://gone.example/list", "https://dead.example/post", "https://moved.example/a", "https://old.example/x", "https://down.example/"} {
upsert(d, site, src, "", "", OriginBing, "2026-11-20")
}
n, err := CheckDue(context.Background(), d, web, site, 0, now)
if err != nil || n != 6 {
t.Fatal(n, err)
}
links, _ := Links(d, site)
got := map[string]Link{}
for _, l := range links {
got[l.Source] = l
}
for src, want := range map[string]string{
"https://kept.example/list": StatusKept, "https://gone.example/list": StatusGone, "https://dead.example/post": StatusPageGone,
"https://moved.example/a": StatusPageGone, "https://old.example/x": StatusTarget404, "https://down.example/": StatusUnchecked,
} {
if got[src].Status != want {
t.Errorf("%s: %s (%s), want %s", src, got[src].Status, got[src].Note, want)
}
}
if k := got["https://kept.example/list"]; k.Target != "/freescout/" || k.LastSeen != "2026-11-24" {
t.Errorf("kept: %+v", k)
}
if o := got["https://old.example/x"]; o.Target != "/old-page/" || !o.Lost() {
t.Errorf("target 404: %+v", o)
}
// Checked: not again within the week, and the day's count is kept.
if n, _ := CheckDue(context.Background(), d, web, site, 0, now.Add(time.Hour)); n != 0 {
t.Errorf("checked again: %d", n)
}
var done int
d.GetJSON(checkedKey("2026-11-24"), &done)
if done != 6 {
t.Errorf("day's count: %d", done)
}
// Adding by hand.
if _, err := Add(d, site, "example.com/x", "", now); err == nil {
t.Error("took an address without https")
}
if _, err := Add(d, site, "https://www.example.com/blog/", "", now); err == nil {
t.Error("took a page of the site itself")
}
l, err := Add(d, site, "https://kept.example/list#comments", "/freescout", now)
if err != nil || l.Origin != OriginBing || l.Target != "/freescout/" {
t.Errorf("added: %+v %v", l, err) // the same link as Bing's, with its target: Bing's row is kept
}
l, err = Add(d, site, "https://friend.example/hosts", "", now)
if err != nil || l.Origin != OriginManual || l.Status != StatusUnchecked {
t.Fatalf("added: %+v %v", l, err)
}
CheckOne(context.Background(), d, web, site, l, now)
if l.Note == "" {
t.Error("no note after a check")
}
}