Files
davidandClaude Opus 5.5 1b2947de7c Phase 9, part 2: one database layer for SQLite and Postgres
db.DB wraps database/sql for either database. The SQL stays SQLite's: on
Postgres each statement's ? become $n and LIKE ignores case as SQLite's
does, and the Postgres schema (postgres.sql, schema 29 as a whole) adds
SQLite's instr, json_extract and two-argument max/min, and a nocase ICU
collation. Needs Postgres 18.

LastInsertId became db.Insert (RETURNING id), INSERT OR IGNORE became ON
CONFLICT DO NOTHING, upserts qualify their columns, and three queries
group by every column they use. SUPERMARKET_TEST_POSTGRES runs the test
suite on Postgres, a new schema per test; all tests pass on both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 07:10:44 -07:00

273 lines
7.6 KiB
Go

// Package backlinks keeps the links from other sites to the company's
// websites: the ones Bing has found, the ones Plausible saw bring visitors
// (the tracking package records those), and ones added by hand; whether
// each is still there; and where a link could be won.
package backlinks
import (
"context"
"fmt"
"net/url"
"slices"
"strings"
"time"
"supermarket/internal/api/bing"
"supermarket/internal/db"
)
// Where a link was found.
const (
OriginBing = "bing"
OriginPlausible = "plausible"
OriginManual = "manual"
)
const dayFormat = "2006-01-02"
// Limits on one Bing read: pages of link counts, how many of the site's
// pages get their linking pages read, and pages of those per page.
const (
maxCountPages = 10
maxTargets = 25
maxLinkPages = 5
bingEvery = 7 * 24 * time.Hour
countsKeyStart = "backlinks:counts:"
)
// Counted is a page of the site with the number of links Bing knows to it.
type Counted struct {
Path string `json:"path"`
URL string `json:"url"`
Count int `json:"count"`
}
// BingState is what the last Bing read found.
type BingState struct {
At time.Time `json:"at"`
First string `json:"first"` // the day of the first read: links seen then aren't "new"
Pages []Counted `json:"pages"` // the site's pages by links to them, most first
Total int `json:"total"`
Linked int `json:"linked"` // linking pages stored this time
Error string `json:"error,omitempty"`
}
func bingKey(site string) string { return countsKeyStart + site }
// LastBing is the last Bing read of a site, or nil.
func LastBing(d *db.DB, site string) (*BingState, error) {
var st BingState
ok, err := d.GetJSON(bingKey(site), &st)
if err != nil || !ok {
return nil, err
}
return &st, nil
}
// DueBing says whether a site's links should be read from Bing again.
func DueBing(d *db.DB, site string, now time.Time) bool {
st, _ := LastBing(d, site)
return st == nil || now.Sub(st.At) > bingEvery
}
// SyncBing reads the links Bing knows to a website: how many to each of
// its pages, and for the most linked pages, which pages link there and
// with what text. bingSite is how Bing names the site; siteURL is the
// website's address in the profile, which the links are kept under.
func SyncBing(ctx context.Context, d *db.DB, c *bing.Client, siteURL, bingSite string, now time.Time) (*BingState, error) {
prev, _ := LastBing(d, siteURL)
st := &BingState{At: now, First: now.Format(dayFormat)}
if prev != nil && prev.First != "" {
st.First = prev.First
}
fail := func(err error) (*BingState, error) {
st.Error = err.Error()
if prev != nil { // keep what was read last time
st.Pages, st.Total, st.First = prev.Pages, prev.Total, prev.First
}
_ = d.PutJSON(bingKey(siteURL), st)
return st, err
}
for page := 0; page < maxCountPages; page++ {
counts, total, err := c.LinkCounts(ctx, bingSite, page)
if err != nil {
return fail(err)
}
for _, lc := range counts {
st.Pages = append(st.Pages, Counted{Path: pathOf(lc.URL), URL: lc.URL, Count: lc.Count})
st.Total += lc.Count
}
if page+1 >= total {
break
}
}
slices.SortStableFunc(st.Pages, func(a, b Counted) int { return b.Count - a.Count })
today := now.Format(dayFormat)
for i, t := range st.Pages {
if i == maxTargets {
break
}
for page := 0; page < maxLinkPages; page++ {
links, total, err := c.URLLinks(ctx, bingSite, t.URL, page)
if err != nil {
return fail(fmt.Errorf("the links to %s: %w", t.Path, err))
}
for _, l := range links {
if l.URL == "" {
continue
}
if err := upsert(d, siteURL, l.URL, t.Path, strings.TrimSpace(l.Anchor), OriginBing, today); err != nil {
return fail(err)
}
st.Linked++
}
if page+1 >= total {
break
}
}
}
return st, d.PutJSON(bingKey(siteURL), st)
}
// upsert keeps a link, first and last seen; a link found again by another
// origin keeps its first origin, and gains an anchor it lacked.
func upsert(d *db.DB, site, source, target, anchor, origin, day string) error {
if u, err := url.Parse(source); err == nil {
u.Fragment = ""
source = u.String()
}
_, err := d.Exec(`INSERT INTO backlinks (site, source_url, target, anchor, origin, first_seen, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (site, source_url, target) DO UPDATE SET
last_seen = max(backlinks.last_seen, excluded.last_seen),
anchor = CASE WHEN backlinks.anchor = '' THEN excluded.anchor ELSE backlinks.anchor END`,
site, source, target, anchor, origin, day, day)
return err
}
// Link is a known link to the site.
type Link struct {
ID int64
Source string // the linking page
Target string // our page's path
Anchor string
Origin string
FirstSeen string
LastSeen string
Status string
CheckedAt time.Time
Note string
}
// Host is the linking page's site, without www.
func (l Link) Host() string { return hostOf(l.Source) }
// Links are a website's known links, newest first.
func Links(d *db.DB, site string) ([]Link, error) {
rows, err := d.Query(`SELECT id, source_url, target, anchor, origin, first_seen, last_seen, status, coalesce(checked_at, ''), note
FROM backlinks WHERE site = ? ORDER BY first_seen DESC, source_url`, site)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Link
for rows.Next() {
var l Link
var checked string
if err := rows.Scan(&l.ID, &l.Source, &l.Target, &l.Anchor, &l.Origin, &l.FirstSeen, &l.LastSeen, &l.Status, &checked, &l.Note); err != nil {
return nil, err
}
l.CheckedAt, _ = time.Parse(time.RFC3339, checked)
out = append(out, l)
}
return out, rows.Err()
}
// Site is a linking site: its links to the website, grouped.
type Site struct {
Host string
Links int // linking pages
Targets []string // our pages it links to, most linked first
Anchors []string // a few of its anchor texts
Example string // one linking page
FirstSeen string
New bool // first seen after the first read
}
// Sites groups a website's links by linking site, new ones first, then by
// how many pages link.
func Sites(links []Link, first string) []Site {
by := map[string]*Site{}
targets := map[string]map[string]int{}
for _, l := range links {
h := l.Host()
s := by[h]
if s == nil {
s = &Site{Host: h, Example: l.Source, FirstSeen: l.FirstSeen}
by[h] = s
targets[h] = map[string]int{}
}
s.Links++
if l.FirstSeen < s.FirstSeen {
s.FirstSeen = l.FirstSeen
}
if l.Target != "" {
targets[h][l.Target]++
}
if l.Anchor != "" && len(s.Anchors) < 3 && !slices.Contains(s.Anchors, l.Anchor) {
s.Anchors = append(s.Anchors, l.Anchor)
}
}
var out []Site
for h, s := range by {
for t := range targets[h] {
s.Targets = append(s.Targets, t)
}
tc := targets[h]
slices.SortFunc(s.Targets, func(a, b string) int {
if tc[a] != tc[b] {
return tc[b] - tc[a]
}
return strings.Compare(a, b)
})
s.New = first != "" && s.FirstSeen > first
out = append(out, *s)
}
slices.SortFunc(out, func(a, b Site) int {
if a.New != b.New {
if a.New {
return -1
}
return 1
}
if a.Links != b.Links {
return b.Links - a.Links
}
return strings.Compare(a.Host, b.Host)
})
return out
}
func hostOf(u string) string {
if p, err := url.Parse(u); err == nil && p.Hostname() != "" {
return strings.TrimPrefix(strings.ToLower(p.Hostname()), "www.")
}
return u
}
// pathOf is a page's path, with a trailing slash, as the site's other
// tables key pages.
func pathOf(u string) string {
p := u
if pu, err := url.Parse(u); err == nil {
p = pu.Path
}
p = strings.ToLower(p)
if !strings.HasSuffix(p, "/") {
p += "/"
}
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
return p
}