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:
@@ -0,0 +1,69 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/api"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/places"
|
||||
)
|
||||
|
||||
// regionReach is how far from a named place a cell may lie and still be
|
||||
// followed with it: a city near a cell's edge brings in the neighbour.
|
||||
const regionReach = 40 // km
|
||||
|
||||
// resolveRegions turns what --region was given into region codes. A 3-character
|
||||
// geohash is taken as it is; anything else is a place name ("bonn", "Cologne",
|
||||
// "München"), which becomes the cell it lies in plus any cell within regionReach
|
||||
// km. A name that looks like a code ("dub") can be forced with "name:dub". The
|
||||
// notes say what each name turned into, so nothing is followed unannounced.
|
||||
func resolveRegions(values []string, load func() ([]places.Place, error)) (regions, notes []string, err error) {
|
||||
var ps []places.Place // loaded on the first name, so plain codes cost nothing
|
||||
add := func(cells ...string) {
|
||||
for _, c := range cells {
|
||||
if !slices.Contains(regions, c) {
|
||||
regions = append(regions, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, v := range values {
|
||||
v = strings.TrimSpace(v)
|
||||
name, forced := strings.CutPrefix(v, "name:")
|
||||
if !forced && listing.ValidRegion(strings.ToLower(v)) {
|
||||
add(strings.ToLower(v))
|
||||
continue
|
||||
}
|
||||
if ps == nil {
|
||||
if ps, err = load(); err != nil || len(ps) == 0 {
|
||||
return nil, nil, fmt.Errorf("--region %q: the list of places is not available (%v); use a 3-character geohash such as u1j", v, err)
|
||||
}
|
||||
}
|
||||
matches := places.Search(ps, name, 5)
|
||||
if len(matches) == 0 {
|
||||
return nil, nil, fmt.Errorf("--region %q is neither a region code (3 geohash characters, e.g. u1j) nor a place I know; check the spelling or try the English or German name", v)
|
||||
}
|
||||
m := matches[0]
|
||||
cells := places.CellsNear(m.Place.Lat, m.Place.Lon, regionReach)
|
||||
shown := m.Place.Name
|
||||
if m.Matched != "" {
|
||||
shown = fmt.Sprintf("%s (%s)", m.Place.Name, m.Matched)
|
||||
}
|
||||
note := fmt.Sprintf("--region %q is %s, %s: following %s", v, shown, m.Place.Country, strings.Join(cells, ", "))
|
||||
if len(matches) > 1 && matches[1].Place.Name != "" && sameName(matches[1], m) {
|
||||
note += fmt.Sprintf(" (other places with that name exist, e.g. in %s; use the region code to be exact)", matches[1].Place.Country)
|
||||
}
|
||||
notes = append(notes, note)
|
||||
add(cells...)
|
||||
}
|
||||
if len(regions) > api.MaxRegions {
|
||||
return nil, nil, fmt.Errorf("--region gives %d regions; a node may follow at most %d", len(regions), api.MaxRegions)
|
||||
}
|
||||
return regions, notes, nil
|
||||
}
|
||||
|
||||
// sameName says whether another match has the same name as the chosen one.
|
||||
func sameName(other, chosen places.Match) bool {
|
||||
return places.Fold(other.Place.Name) == places.Fold(chosen.Place.Name) && other.Place.Country != chosen.Place.Country
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/places"
|
||||
)
|
||||
|
||||
func realPlaces() ([]places.Place, error) { return places.Load(os.DirFS("../../web/dist")) }
|
||||
|
||||
func TestCodesPassThroughWithoutLoadingPlaces(t *testing.T) {
|
||||
loaded := false
|
||||
got, notes, err := resolveRegions([]string{"u1j", " U1X ", "u1j"}, func() ([]places.Place, error) {
|
||||
loaded = true
|
||||
return nil, nil
|
||||
})
|
||||
if err != nil || loaded || len(notes) != 0 || !reflect.DeepEqual(got, []string{"u1j", "u1x"}) {
|
||||
t.Fatalf("got %v notes %v loaded=%v err=%v", got, notes, loaded, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestANameBecomesItsCellsAndSaysSo(t *testing.T) {
|
||||
got, notes, err := resolveRegions([]string{"bonn", "Cologne"}, realPlaces)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got[0] != "u1j" {
|
||||
t.Fatalf("Bonn's own cell comes first: %v", got)
|
||||
}
|
||||
if len(notes) != 2 || !strings.Contains(notes[0], "Bonn") || !strings.Contains(notes[1], "Köln (Cologne)") {
|
||||
t.Fatalf("notes = %q", notes)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, r := range got {
|
||||
if seen[r] {
|
||||
t.Fatalf("repeated region in %v", got)
|
||||
}
|
||||
seen[r] = true
|
||||
}
|
||||
}
|
||||
|
||||
func TestACodeAndANameMix(t *testing.T) {
|
||||
got, _, err := resolveRegions([]string{"u30", "Bonn"}, realPlaces)
|
||||
if err != nil || got[0] != "u30" || got[1] != "u1j" {
|
||||
t.Fatalf("got %v err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUnknownNameIsRefusedWithAHint(t *testing.T) {
|
||||
_, _, err := resolveRegions([]string{"Atlantisxyz"}, realPlaces)
|
||||
if err == nil || !strings.Contains(err.Error(), "neither a region code") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestANameThatLooksLikeACodeCanBeForced(t *testing.T) {
|
||||
got, notes, err := resolveRegions([]string{"name:dublin"}, realPlaces)
|
||||
if err != nil || len(notes) != 1 || !strings.Contains(notes[0], "Dublin") || len(got) == 0 {
|
||||
t.Fatalf("got %v notes %v err=%v", got, notes, err)
|
||||
}
|
||||
// Without the prefix, "dub" is a valid code and is taken as one.
|
||||
got, notes, err = resolveRegions([]string{"dub"}, realPlaces)
|
||||
if err != nil || len(notes) != 0 || !reflect.DeepEqual(got, []string{"dub"}) {
|
||||
t.Fatalf("dub: %v %v %v", got, notes, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNamesNeedThePlaceList(t *testing.T) {
|
||||
_, _, err := resolveRegions([]string{"Bonn"}, func() ([]places.Place, error) { return nil, errors.New("gone") })
|
||||
if err == nil || !strings.Contains(err.Error(), "not available") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTooManyRegionsAreRefused(t *testing.T) {
|
||||
var many []string
|
||||
for _, c := range "0123456789bcdefghjkmn" {
|
||||
many = append(many, "u0"+string(c))
|
||||
}
|
||||
_, _, err := resolveRegions(many, nil)
|
||||
if err == nil || !strings.Contains(err.Error(), "at most") {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
// remindWithin is how close to its end a listing gets a reminder. It
|
||||
// matches the web UI, which marks a listing in this range as running out.
|
||||
remindWithin = 5 * 24 * time.Hour
|
||||
// remindAgain is how long a reminder for one listing keeps quiet. Renewing
|
||||
// is manual on purpose (an abandoned listing should lapse), so the node
|
||||
// reminds, but not on every check.
|
||||
remindAgain = 24 * time.Hour
|
||||
// remindCheckEvery is how often the node looks; remindFirst waits until the
|
||||
// start-up lines (the sign-in link) have been printed and read.
|
||||
remindCheckEvery = time.Hour
|
||||
remindFirst = 20 * time.Second
|
||||
)
|
||||
|
||||
// reminder tells the owner on the terminal which listings are about to lapse.
|
||||
type reminder struct {
|
||||
list func(context.Context) ([]*listing.Listing, error)
|
||||
log *slog.Logger
|
||||
httpAddr string
|
||||
now func() time.Time
|
||||
said map[string]time.Time // listing id -> when it was last mentioned
|
||||
}
|
||||
|
||||
// check says one line for each listing that ends within remindWithin and has
|
||||
// not been mentioned lately. It returns how many it mentioned.
|
||||
func (r *reminder) check(ctx context.Context) int {
|
||||
ls, err := r.list(ctx)
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
r.log.Debug("could not check for expiring listings", "err", err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
now := r.now()
|
||||
n := 0
|
||||
for _, l := range ls {
|
||||
end := time.Unix(l.ExpiresAt, 0)
|
||||
left := end.Sub(now)
|
||||
if left > remindWithin || left <= 0 {
|
||||
continue
|
||||
}
|
||||
if t, ok := r.said[l.ID]; ok && now.Sub(t) < remindAgain {
|
||||
continue
|
||||
}
|
||||
r.said[l.ID] = now
|
||||
n++
|
||||
r.log.Warn("a listing runs out soon: renew it, or it disappears",
|
||||
"listing", l.Title,
|
||||
"ends", end.Local().Format("2006-01-02 15:04"),
|
||||
"left", leftText(left),
|
||||
"renew", uiURL(r.httpAddr, "/mine"))
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// leftText is the time left, rounded the way a person reads it.
|
||||
func leftText(d time.Duration) string {
|
||||
switch {
|
||||
case d >= 36*time.Hour:
|
||||
return fmt.Sprintf("%d days", int((d+12*time.Hour)/(24*time.Hour)))
|
||||
case d >= time.Hour:
|
||||
return fmt.Sprintf("%d hours", int(d/time.Hour))
|
||||
default:
|
||||
return "less than an hour"
|
||||
}
|
||||
}
|
||||
|
||||
// remindExpiring watches the owner's listings until ctx ends.
|
||||
func remindExpiring(ctx context.Context, log *slog.Logger, st *store.Store, author, httpAddr string) {
|
||||
r := &reminder{
|
||||
list: func(ctx context.Context) ([]*listing.Listing, error) { return st.ByAuthor(ctx, author) },
|
||||
log: log,
|
||||
httpAddr: httpAddr,
|
||||
now: time.Now,
|
||||
said: map[string]time.Time{},
|
||||
}
|
||||
timer := time.NewTimer(remindFirst)
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
r.check(ctx)
|
||||
timer.Reset(remindCheckEvery)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
)
|
||||
|
||||
func testReminder(now *time.Time, ls ...*listing.Listing) (*reminder, *bytes.Buffer) {
|
||||
var out bytes.Buffer
|
||||
log := slog.New(slog.NewTextHandler(&out, &slog.HandlerOptions{ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
|
||||
if a.Key == slog.TimeKey {
|
||||
return slog.Attr{}
|
||||
}
|
||||
return a
|
||||
}}))
|
||||
return &reminder{
|
||||
list: func(context.Context) ([]*listing.Listing, error) { return ls, nil },
|
||||
log: log,
|
||||
httpAddr: "0.0.0.0:8080",
|
||||
now: func() time.Time { return *now },
|
||||
said: map[string]time.Time{},
|
||||
}, &out
|
||||
}
|
||||
|
||||
func ends(id, title string, in time.Duration, now time.Time) *listing.Listing {
|
||||
return &listing.Listing{ID: id, Title: title, ExpiresAt: now.Add(in).Unix()}
|
||||
}
|
||||
|
||||
func TestOnlyListingsThatRunOutSoonAreMentioned(t *testing.T) {
|
||||
now := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)
|
||||
r, out := testReminder(&now,
|
||||
ends("a", "Far away", 20*24*time.Hour, now),
|
||||
ends("b", "Soon", 3*24*time.Hour, now),
|
||||
ends("c", "Edge", remindWithin, now),
|
||||
ends("d", "Already over", -time.Hour, now),
|
||||
)
|
||||
if n := r.check(context.Background()); n != 2 {
|
||||
t.Fatalf("mentioned %d, want 2:\n%s", n, out)
|
||||
}
|
||||
got := out.String()
|
||||
for _, want := range []string{"level=WARN", "listing=Soon", "left=\"3 days\"", "listing=Edge", "left=\"5 days\"",
|
||||
"renew=http://127.0.0.1:8080/#/mine"} { // a wildcard bind opens on loopback
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q in:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
for _, no := range []string{"Far away", "Already over", "token", "login"} {
|
||||
if strings.Contains(got, no) {
|
||||
t.Errorf("%q must not appear:\n%s", no, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAListingIsMentionedOncePerDayNotOnEveryCheck(t *testing.T) {
|
||||
now := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)
|
||||
r, _ := testReminder(&now, ends("b", "Soon", 4*24*time.Hour, now))
|
||||
ls := func() int { return r.check(context.Background()) }
|
||||
if ls() != 1 {
|
||||
t.Fatal("the first check must mention it")
|
||||
}
|
||||
now = now.Add(time.Hour)
|
||||
if ls() != 0 {
|
||||
t.Fatal("an hour later it must stay quiet")
|
||||
}
|
||||
now = now.Add(remindAgain)
|
||||
if ls() != 1 {
|
||||
t.Fatal("a day later it must say it again")
|
||||
}
|
||||
}
|
||||
|
||||
func TestARenewedListingIsNotMentioned(t *testing.T) {
|
||||
now := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)
|
||||
l := ends("b", "Soon", 2*24*time.Hour, now)
|
||||
r, _ := testReminder(&now, l)
|
||||
if r.check(context.Background()) != 1 {
|
||||
t.Fatal("expected a reminder")
|
||||
}
|
||||
l.ExpiresAt = now.Add(30 * 24 * time.Hour).Unix() // renewed in the browser
|
||||
now = now.Add(2 * remindAgain)
|
||||
if r.check(context.Background()) != 0 {
|
||||
t.Fatal("a renewed listing must not be mentioned")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFailingStoreIsNotAReminder(t *testing.T) {
|
||||
now := time.Now()
|
||||
r, out := testReminder(&now)
|
||||
r.list = func(context.Context) ([]*listing.Listing, error) { return nil, errors.New("db closed") }
|
||||
if r.check(context.Background()) != 0 || strings.Contains(out.String(), "WARN") {
|
||||
t.Fatalf("a read error is not a warning to the owner:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeLeftReadsLikeAPerson(t *testing.T) {
|
||||
for d, want := range map[time.Duration]string{
|
||||
5 * 24 * time.Hour: "5 days", 49 * time.Hour: "2 days", 36 * time.Hour: "2 days",
|
||||
30 * time.Hour: "30 hours", 3 * time.Hour: "3 hours", 20 * time.Minute: "less than an hour",
|
||||
} {
|
||||
if got := leftText(d); got != want {
|
||||
t.Errorf("%v: %q, want %q", d, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-1
@@ -22,7 +22,9 @@ import (
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/places"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
"git.stinnesbeck.com/nils/allmende/web"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -35,7 +37,7 @@ func cmdRun(args []string) error {
|
||||
fs := flag.NewFlagSet("run", flag.ExitOnError)
|
||||
data := dataFlag(fs)
|
||||
var regions, bootstrap, listen listFlag
|
||||
fs.Var(®ions, "region", "geohash region (3 characters, e.g. u1x) to replicate; repeatable")
|
||||
fs.Var(®ions, "region", "region to replicate: a 3-character geohash (u1x) or a place name (\"Bonn\", \"Köln\"); repeatable")
|
||||
fs.Var(&bootstrap, "bootstrap", "extra bootstrap peer: …/p2p/<id> or /dnsaddr/<name>; repeatable")
|
||||
noDefaultBootstrap := fs.Bool("no-default-bootstrap", false,
|
||||
"do not use the built-in bootstrap name "+p2p.DefaultBootstrap)
|
||||
@@ -53,6 +55,16 @@ func cmdRun(args []string) error {
|
||||
"how many new conversations each of your listings can start per day")
|
||||
fs.Parse(args)
|
||||
|
||||
// Place names become region codes; say what each one turned into.
|
||||
codes, notes, err := resolveRegions(regions, func() ([]places.Place, error) { return places.Load(web.Files()) })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range notes {
|
||||
fmt.Fprintln(os.Stderr, n)
|
||||
}
|
||||
regions = codes
|
||||
|
||||
// Regions the owner chose in the browser win over --region, which then only
|
||||
// says where a node starts the first time.
|
||||
saved, ok, err := loadRegions(*data)
|
||||
@@ -193,6 +205,7 @@ func cmdRun(args []string) error {
|
||||
|
||||
go announce(ctx, log, node, st, dev.Cert.Author)
|
||||
go watchInbox(ctx, log, in)
|
||||
go remindExpiring(ctx, log, st, dev.Cert.Author, ln.Addr().String())
|
||||
|
||||
<-ctx.Done()
|
||||
log.Info("shutting down")
|
||||
|
||||
Reference in New Issue
Block a user