Place names for --region, an expiry reminder, and e2e checks through the UI

--region takes a place name as well as a code ("Bonn", "Köln", "cologne",
"name:dub" to force a name that looks like a code). The node uses the same
GeoNames list as the browser (internal/places), follows the place's cell plus
any cell within 40 km, and prints what each name became.

The node reminds the owner on its terminal, once a day per listing, about
every listing with 5 days or less left (the UI marks the same range). The
sign-in token is never in the line.

scripts/e2e/ui.ts drives the real bundle in jsdom against real nodes: a buyer
writes from a listing page, the owner reads and answers in their own page and
the buyer's page shows the verified answer; a node with no region gets its
first one by place name in the browser and keeps it over a restart. e2e.sh
also checks --region by name and the reminder, and keeps its scratch files in
the checkout's .tmp.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-18 10:51:56 +01:00
co-authored by Claude Sonnet 5.5
parent e3d0c12e55
commit 6995364edc
10 changed files with 903 additions and 5 deletions
+218
View File
@@ -0,0 +1,218 @@
// Package places finds regions by place name, offline, with the same list of
// cities the browser uses (GeoNames, CC BY 4.0; see web/scripts/places.mjs).
//
// A region is a 3-character geohash cell, about 100 to 150 km wide: right for
// the network, meaningless to a person. "Bonn" or "Cologne" is turned into the
// cell it lies in plus any other cell within a few dozen kilometres, so a city
// near a cell's edge does not miss the listings just across it.
package places
import (
"bufio"
"io/fs"
"math"
"slices"
"sort"
"strconv"
"strings"
"unicode"
"golang.org/x/text/unicode/norm"
)
// File is the list's name in the embedded UI.
const File = "places.tsv"
// Place is a city.
type Place struct {
Name string
Lat, Lon float64
Country string // ISO code
Population int
Alts []string // other names (Köln: Cologne)
keys []string // folded: the name, the alternatives, then the ASCII spelling
}
// Match is a place that fits a query.
type Match struct {
Place *Place
// Matched is the name that fit, when it is not the place's main name.
Matched string
score int
}
// Fold lower-cases and strips accents, with ß as ss: "Zürich", "zurich" and
// "ZÜRICH" are one key.
func Fold(s string) string {
s = strings.ReplaceAll(s, "ß", "ss")
var b strings.Builder
for _, r := range norm.NFD.String(s) {
if unicode.Is(unicode.Mn, r) {
continue
}
b.WriteRune(unicode.ToLower(r))
}
return b.String()
}
// unTranslit undoes how a keyboard without umlauts writes them:
// "muenchen" becomes "munchen", which is what Fold makes of "München".
func unTranslit(s string) string {
return strings.NewReplacer("ae", "a", "oe", "o", "ue", "u").Replace(s)
}
// Load reads the list from fsys (the embedded UI): name, ASCII name, latitude,
// longitude, country, population, alternatives, tab-separated.
func Load(fsys fs.FS) ([]Place, error) {
f, err := fsys.Open(File)
if err != nil {
return nil, err
}
defer f.Close()
var out []Place
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 0, 64<<10), 1<<20)
for sc.Scan() {
cols := strings.Split(sc.Text(), "\t")
if len(cols) < 6 {
continue
}
lat, err1 := strconv.ParseFloat(cols[2], 64)
lon, err2 := strconv.ParseFloat(cols[3], 64)
if cols[0] == "" || err1 != nil || err2 != nil {
continue
}
pop, _ := strconv.Atoi(cols[5])
p := Place{Name: cols[0], Lat: lat, Lon: lon, Country: cols[4], Population: pop}
if len(cols) > 6 && cols[6] != "" {
p.Alts = strings.Split(cols[6], "|")
}
p.keys = append(p.keys, Fold(p.Name))
for _, a := range p.Alts {
p.keys = append(p.keys, Fold(a))
}
if cols[1] != "" {
p.keys = append(p.keys, Fold(cols[1])) // "Koeln": found, but shown as "Köln"
}
out = append(out, p)
}
return out, sc.Err()
}
func score(key, q string) int {
switch {
case key == q:
return 0
case strings.HasPrefix(key, q):
return 1
case slices.ContainsFunc(strings.FieldsFunc(key, func(r rune) bool { return r == ' ' || r == '-' }),
func(w string) bool { return strings.HasPrefix(w, q) }):
return 2
case len(q) >= 3 && strings.Contains(key, q):
return 3
}
return 4
}
// Search returns the best matches for query: exact names first, then by size.
func Search(places []Place, query string, limit int) []Match {
q1 := Fold(strings.TrimSpace(query))
if len([]rune(q1)) < 2 {
return nil
}
qs := []string{q1}
if q2 := unTranslit(q1); q2 != q1 {
qs = append(qs, q2)
}
var hits []Match
for i := range places {
p := &places[i]
best, bestKey := 4, 0
for k, key := range p.keys {
for _, q := range qs {
if s := score(key, q); s < best {
best, bestKey = s, k
}
}
}
if best == 4 {
continue
}
m := Match{Place: p, score: best}
// Keys after the alternatives are the ASCII spelling of the main name.
if bestKey >= 1 && bestKey <= len(p.Alts) {
m.Matched = p.Alts[bestKey-1]
}
hits = append(hits, m)
}
sort.SliceStable(hits, func(i, j int) bool {
if hits[i].score != hits[j].score {
return hits[i].score < hits[j].score
}
return hits[i].Place.Population > hits[j].Place.Population
})
if len(hits) > limit {
hits = hits[:limit]
}
return hits
}
const base32 = "0123456789bcdefghjkmnpqrstuvwxyz"
// Encode is the geohash of a position, precision characters long.
func Encode(lat, lon float64, precision int) string {
latR, lonR := [2]float64{-90, 90}, [2]float64{-180, 180}
var out []byte
bits, value := 0, 0
even := true
for len(out) < precision {
r, x := &latR, lat
if even {
r, x = &lonR, lon
}
mid := (r[0] + r[1]) / 2
value <<= 1
if x >= mid {
value |= 1
r[0] = mid
} else {
r[1] = mid
}
even = !even
if bits++; bits == 5 {
out = append(out, base32[value])
bits, value = 0, 0
}
}
return string(out)
}
// RegionPrecision is the length of a region's geohash.
const RegionPrecision = 3
const kmPerDegree = 111.2
// CellsNear returns the regions to follow for a position: the cell it lies in
// first, then any other cell within about km of it.
func CellsNear(lat, lon, km float64) []string {
cell := func(la, lo float64) string {
la = math.Max(-89.999, math.Min(89.999, la))
lo = math.Mod(math.Mod(lo+180, 360)+360, 360) - 180
return Encode(la, lo, RegionPrecision)
}
out := []string{cell(lat, lon)}
dLat := 1 / kmPerDegree
dLon := 1 / (kmPerDegree * math.Max(0.05, math.Cos(lat*math.Pi/180)))
// Two rings (half and full distance) in 16 directions: a cell clipping the
// circle anywhere is hit by one of them.
for _, r := range []float64{km / 2, km} {
for i := 0; i < 16; i++ {
a := float64(i) / 16 * 2 * math.Pi
c := cell(lat+math.Sin(a)*r*dLat, lon+math.Cos(a)*r*dLon)
if !slices.Contains(out, c) {
out = append(out, c)
}
}
}
return out
}
+101
View File
@@ -0,0 +1,101 @@
package places
import (
"os"
"testing"
)
// The real list the node ships (web/dist is the one it embeds).
func load(t *testing.T) []Place {
t.Helper()
ps, err := Load(os.DirFS("../../web/dist"))
if err != nil {
t.Fatal(err)
}
if len(ps) < 30000 {
t.Fatalf("only %d places", len(ps))
}
return ps
}
func first(t *testing.T, ps []Place, q string) Match {
t.Helper()
m := Search(ps, q, 1)
if len(m) == 0 {
t.Fatalf("%q: nothing found", q)
}
return m[0]
}
func TestNamesAreFoundHoweverTheyAreSpelled(t *testing.T) {
ps := load(t)
for q, name := range map[string]string{
"Bonn": "Bonn", "bonn": "Bonn", "köln": "Köln", "koeln": "Köln", "KOELN": "Köln",
"zurich": "Zürich", "Zürich": "Zürich",
} {
if got := first(t, ps, q).Place.Name; got != name {
t.Errorf("%q: found %q, want %q", q, got, name)
}
}
}
func TestOtherLanguagesLeadToThePlaceAndSayWhatMatched(t *testing.T) {
ps := load(t)
m := first(t, ps, "cologne")
if m.Place.Name != "Köln" || m.Matched != "Cologne" {
t.Fatalf("cologne: %s (%s)", m.Place.Name, m.Matched)
}
for q, cc := range map[string]string{"münchen": "DE", "muenchen": "DE", "nuernberg": "DE", "prag": "CZ", "wien": "AT"} {
if got := first(t, ps, q).Place.Country; got != cc {
t.Errorf("%q: country %s, want %s", q, got, cc)
}
}
if first(t, ps, "Köln").Matched != "" {
t.Error("the main name is not repeated")
}
}
func TestTheBigCityWinsOverASmallNamesake(t *testing.T) {
ps := load(t)
v := Search(ps, "vienna", 5)
if v[0].Place.Country != "AT" {
t.Fatalf("first is %s", v[0].Place.Country)
}
if Search(ps, "b", 5) != nil || Search(ps, "qqqzzzxxx", 5) != nil || Search(ps, " ", 5) != nil {
t.Error("too short or unknown queries must find nothing")
}
}
func TestGeohashesAndCells(t *testing.T) {
// Known values: the geohash of Hamburg's centre starts u1x, Bonn is in u1j.
if got := Encode(57.64911, 10.40744, 11); got != "u4pruydqqvj" {
t.Fatalf("Encode = %s (the standard test vector)", got)
}
ps := load(t)
bonn := first(t, ps, "Bonn").Place
cells := CellsNear(bonn.Lat, bonn.Lon, 40)
if cells[0] != "u1j" {
t.Fatalf("Bonn's own cell comes first: %v", cells)
}
seen := map[string]bool{}
for _, c := range cells {
if seen[c] || len(c) != 3 {
t.Fatalf("bad or repeated cell in %v", cells)
}
seen[c] = true
}
// The middle of a cell is far from every edge; at 80 km its neighbours are in reach.
if got := CellsNear(50.9, 7.2, 1); len(got) != 1 {
t.Fatalf("a tiny reach stays in one cell: %v", got)
}
if got := CellsNear(50.9, 7.2, 80); len(got) < 2 {
t.Fatalf("a wide reach crosses a border: %v", got)
}
for _, p := range [][2]float64{{89.99, 0}, {-89.99, 10}, {0, 179.99}, {0, -179.99}, {64.1, -21.9}} {
for _, c := range CellsNear(p[0], p[1], 40) {
if len(c) != 3 {
t.Fatalf("%v: %v", p, c)
}
}
}
}