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:
@@ -30,12 +30,15 @@ node says so on its terminal (listing, link to the conversation, never the text)
|
|||||||
|
|
||||||
Owners publish from the same screen: "New listing" takes a title, price and
|
Owners publish from the same screen: "New listing" takes a title, price and
|
||||||
pasted coordinates (only a ~1 km area is published, never the address), and
|
pasted coordinates (only a ~1 km area is published, never the address), and
|
||||||
listings can be edited, renewed (30 days, manually) or deleted there.
|
listings can be edited, renewed (30 days, manually) or deleted there. Renewing is
|
||||||
|
manual on purpose, so abandoned listings lapse; the node reminds you on its
|
||||||
|
terminal, once a day, about every listing with 5 days or less left.
|
||||||
|
|
||||||
**Regions** are the areas a node keeps listings for (3-character geohash cells,
|
**Regions** are the areas a node keeps listings for (3-character geohash cells,
|
||||||
about 100 to 150 km wide). A new node follows none: the owner chooses them in the
|
about 100 to 150 km wide). A new node follows none: the owner chooses them in the
|
||||||
browser, "My listings", then "Regions" (or `--region` sets them at the first start).
|
browser, "My listings", then "Regions", or `--region` sets them at the first start:
|
||||||
Search a place
|
a region code (`--region u1j`) or a place name (`--region Bonn --region "Köln"`;
|
||||||
|
the node says which cells a name became). Search a place
|
||||||
by name (Bonn, Cologne, München, …); the page offers the place's own cell and any
|
by name (Bonn, Cologne, München, …); the page offers the place's own cell and any
|
||||||
cell within about 40 km, and the change applies at once, without a restart. The
|
cell within about 40 km, and the change applies at once, without a restart. The
|
||||||
choice is kept in `regions.json` in the data directory and wins over `--region`
|
choice is kept in `regions.json` in the data directory and wins over `--region`
|
||||||
|
|||||||
@@ -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/listing"
|
||||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||||
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
"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/internal/store"
|
||||||
|
"git.stinnesbeck.com/nils/allmende/web"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -35,7 +37,7 @@ func cmdRun(args []string) error {
|
|||||||
fs := flag.NewFlagSet("run", flag.ExitOnError)
|
fs := flag.NewFlagSet("run", flag.ExitOnError)
|
||||||
data := dataFlag(fs)
|
data := dataFlag(fs)
|
||||||
var regions, bootstrap, listen listFlag
|
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")
|
fs.Var(&bootstrap, "bootstrap", "extra bootstrap peer: …/p2p/<id> or /dnsaddr/<name>; repeatable")
|
||||||
noDefaultBootstrap := fs.Bool("no-default-bootstrap", false,
|
noDefaultBootstrap := fs.Bool("no-default-bootstrap", false,
|
||||||
"do not use the built-in bootstrap name "+p2p.DefaultBootstrap)
|
"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")
|
"how many new conversations each of your listings can start per day")
|
||||||
fs.Parse(args)
|
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
|
// Regions the owner chose in the browser win over --region, which then only
|
||||||
// says where a node starts the first time.
|
// says where a node starts the first time.
|
||||||
saved, ok, err := loadRegions(*data)
|
saved, ok, err := loadRegions(*data)
|
||||||
@@ -193,6 +205,7 @@ func cmdRun(args []string) error {
|
|||||||
|
|
||||||
go announce(ctx, log, node, st, dev.Cert.Author)
|
go announce(ctx, log, node, st, dev.Cert.Author)
|
||||||
go watchInbox(ctx, log, in)
|
go watchInbox(ctx, log, in)
|
||||||
|
go remindExpiring(ctx, log, st, dev.Cert.Author, ln.Addr().String())
|
||||||
|
|
||||||
<-ctx.Done()
|
<-ctx.Done()
|
||||||
log.Info("shutting down")
|
log.Info("shutting down")
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+49
-1
@@ -9,7 +9,8 @@ ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
|||||||
[ -d "$ROOT/web/node_modules" ] || { echo "web dependencies missing: run 'cd web && npm ci' first"; exit 1; }
|
[ -d "$ROOT/web/node_modules" ] || { echo "web dependencies missing: run 'cd web && npm ci' first"; exit 1; }
|
||||||
(cd "$ROOT" && go build -o bin/allmende ./cmd/allmende) || exit 1
|
(cd "$ROOT" && go build -o bin/allmende ./cmd/allmende) || exit 1
|
||||||
BIN=$ROOT/bin/allmende
|
BIN=$ROOT/bin/allmende
|
||||||
W=$(mktemp -d "${TMPDIR:-/tmp}/allmende-e2e.XXXXXX")
|
mkdir -p "$ROOT/.tmp" # scratch space inside the checkout (git ignores it), not /tmp
|
||||||
|
W=$(mktemp -d "${TMPDIR:-$ROOT/.tmp}/allmende-e2e.XXXXXX")
|
||||||
A=$W/a; B=$W/b
|
A=$W/a; B=$W/b
|
||||||
PIDS=()
|
PIDS=()
|
||||||
cleanup() {
|
cleanup() {
|
||||||
@@ -119,6 +120,11 @@ ok "buyer's browser code verified and read the grant from B"
|
|||||||
node $BUYER read http://127.0.0.1:18102 $AUTHOR $ID $(node -e 'console.log("77".repeat(32))') | grep -q . && bad "another thread key saw a reply"
|
node $BUYER read http://127.0.0.1:18102 $AUTHOR $ID $(node -e 'console.log("77".repeat(32))') | grep -q . && bad "another thread key saw a reply"
|
||||||
ok "a different thread key sees nothing"
|
ok "a different thread key sees nothing"
|
||||||
|
|
||||||
|
echo "== the same through the web UI: a real page for the buyer on B, one for the owner on A"
|
||||||
|
UI=$ROOT/scripts/e2e/ui.ts
|
||||||
|
node $UI buyer http://127.0.0.1:18102 http://127.0.0.1:18101 $TOKEN $AUTHOR $ID > $W/ui-buyer.txt 2>&1 \
|
||||||
|
&& { sed 's/^OK /PASS: UI: /' $W/ui-buyer.txt; } || { cat $W/ui-buyer.txt; bad "the buyer flow through the web UI"; }
|
||||||
|
|
||||||
echo "== recover on A (simulate a stolen machine)"
|
echo "== recover on A (simulate a stolen machine)"
|
||||||
OLD_DEVICE=$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["device"])')
|
OLD_DEVICE=$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["device"])')
|
||||||
kill ${PIDS[0]}; wait ${PIDS[0]} 2>/dev/null
|
kill ${PIDS[0]}; wait ${PIDS[0]} 2>/dev/null
|
||||||
@@ -176,4 +182,46 @@ wait_for "X restarted" 10 curl -sf http://127.0.0.1:18104/api/v1/status
|
|||||||
wait_for "X reconnects from its remembered peers" 30 check ge 1 peers 18104
|
wait_for "X reconnects from its remembered peers" 30 check ge 1 peers 18104
|
||||||
ok "X rejoined the network with no bootstrap configured"
|
ok "X rejoined the network with no bootstrap configured"
|
||||||
|
|
||||||
|
echo "== regions: chosen by place name in the browser, even the first one"
|
||||||
|
D=$W/d
|
||||||
|
$BIN init --data $D >/dev/null || bad "init D"
|
||||||
|
# No --region: the node starts empty and says what to do.
|
||||||
|
$BIN run --data $D --no-mdns --no-default-bootstrap --difficulty $DIFF --http 127.0.0.1:18106 \
|
||||||
|
--listen /ip4/127.0.0.1/tcp/14106 2> $W/d.log &
|
||||||
|
DPID=$!; PIDS+=($DPID)
|
||||||
|
wait_for "D http" 10 curl -sf http://127.0.0.1:18106/api/v1/status
|
||||||
|
grep -q "follows no region yet" $W/d.log && ok "a node without a region starts and tells the owner what to do" || bad "no hint for the owner"
|
||||||
|
DTOKEN=$(cat $D/admin.token)
|
||||||
|
node $UI regions http://127.0.0.1:18106 $DTOKEN > $W/ui-regions.txt 2>&1 \
|
||||||
|
&& { sed 's/^OK /PASS: UI: /' $W/ui-regions.txt; } || { cat $W/ui-regions.txt; bad "choosing the first region through the web UI"; }
|
||||||
|
[ -s $D/regions.json ] && ok "the choice is saved in the data directory" || bad "regions.json missing"
|
||||||
|
kill $DPID; wait $DPID 2>/dev/null
|
||||||
|
$BIN run --data $D --no-mdns --no-default-bootstrap --difficulty $DIFF --http 127.0.0.1:18106 \
|
||||||
|
--listen /ip4/127.0.0.1/tcp/14106 2> $W/d2.log &
|
||||||
|
DPID=$!; PIDS+=($DPID)
|
||||||
|
wait_for "D restarted" 10 curl -sf http://127.0.0.1:18106/api/v1/status
|
||||||
|
curl -s http://127.0.0.1:18106/api/v1/status | grep -q '"regions":\["u1j"' && ok "after a restart without --region it still follows what the browser chose" || bad "regions were lost on restart"
|
||||||
|
|
||||||
|
echo "== --region takes place names"
|
||||||
|
$BIN run --data $W/nope --region Atlantisxyz 2>&1 | grep -q "neither a region code" && ok "an unknown place is refused with a hint" || bad "unknown place was not refused"
|
||||||
|
E=$W/e
|
||||||
|
$BIN init --data $E >/dev/null || bad "init E"
|
||||||
|
$BIN run --data $E --region cologne --no-mdns --no-default-bootstrap --difficulty $DIFF --http 127.0.0.1:18107 \
|
||||||
|
--listen /ip4/127.0.0.1/tcp/14107 2> $W/e.log &
|
||||||
|
PIDS+=($!)
|
||||||
|
wait_for "E http" 10 curl -sf http://127.0.0.1:18107/api/v1/status
|
||||||
|
grep -q 'Köln (Cologne)' $W/e.log && ok "'cologne' is announced as Köln, with the cells it follows" || bad "no note about what the name turned into"
|
||||||
|
curl -s http://127.0.0.1:18107/api/v1/status | grep -q '"regions":\["u1h"' && ok "Cologne's own cell (u1h) comes first" || bad "wrong region for cologne: $(curl -s http://127.0.0.1:18107/api/v1/status)"
|
||||||
|
|
||||||
|
echo "== a listing that runs out soon is reminded on the owner's terminal"
|
||||||
|
SOON='{"kind":"rent","category":"room","geohash":"u1jjjj","price":{"amount_cents":50000,"currency":"EUR","period":"month"},"title":"Zimmer, nur noch kurz","expires_in_days":3}'
|
||||||
|
curl -s -o /dev/null -w "%{http_code}" -X POST -H "Authorization: Bearer $DTOKEN" -d "$SOON" http://127.0.0.1:18106/api/v1/listings | grep -qE "^(200|201)$" || bad "could not publish the short listing on D"
|
||||||
|
wait_for "D's terminal reminds about the listing" 60 grep -q 'a listing runs out soon' $W/d2.log
|
||||||
|
grep 'a listing runs out soon' $W/d2.log | grep -q 'listing="Zimmer, nur noch kurz"' && ok "the reminder names the listing" || bad "reminder does not name the listing"
|
||||||
|
grep 'a listing runs out soon' $W/d2.log | grep -q 'left="3 days"' && ok "and says how long is left" || bad "reminder does not say how long is left"
|
||||||
|
grep 'a listing runs out soon' $W/d2.log | grep -q "renew=http://127.0.0.1:18106/#/mine" && ok "and links to where to renew" || bad "reminder has no link"
|
||||||
|
grep 'a listing runs out soon' $W/d2.log | grep -q "$DTOKEN" && bad "the sign-in token leaked into the log"
|
||||||
|
ok "the reminder does not carry the sign-in token"
|
||||||
|
grep -q "Helle Wohnung" $W/d2.log && bad "a listing with plenty of time left was reminded"
|
||||||
|
|
||||||
echo "ALL E2E CHECKS PASSED"
|
echo "ALL E2E CHECKS PASSED"
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
// Drives the real web UI against real nodes, for the e2e script. The page is
|
||||||
|
// the built bundle (web/dist) in jsdom; every request goes to a running node,
|
||||||
|
// nothing is faked. Usage:
|
||||||
|
//
|
||||||
|
// node ui.ts regions <node url> <admin token>
|
||||||
|
// a node with no region: the owner signs in, picks a place by name, saves
|
||||||
|
// node ui.ts buyer <buyer node url> <owner node url> <admin token> <author> <listing id>
|
||||||
|
// a buyer writes from a listing page; the owner reads and answers in
|
||||||
|
// their own page; the buyer's page shows the verified answer
|
||||||
|
//
|
||||||
|
// Prints "OK …" for each step and exits non-zero on the first failure.
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { JSDOM, type DOMWindow } from "../../web/node_modules/jsdom/lib/api.js";
|
||||||
|
|
||||||
|
const dist = new URL("../../web/dist/", import.meta.url);
|
||||||
|
const html = readFileSync(new URL("index.html", dist), "utf8");
|
||||||
|
const bundle = readFileSync(new URL("app.js", dist), "utf8");
|
||||||
|
const places = readFileSync(new URL("places.tsv", dist));
|
||||||
|
|
||||||
|
interface Page {
|
||||||
|
w: DOMWindow;
|
||||||
|
d: Document;
|
||||||
|
waitFor(pred: () => boolean, what: string, ms?: number): Promise<void>;
|
||||||
|
close(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs the bundle against `node`, as a browser tab opened on that node would. */
|
||||||
|
function open(node: string, hash: string): Page {
|
||||||
|
const dom = new JSDOM(html, { url: `${node}/?lang=en${hash}`, runScripts: "outside-only", pretendToBeVisual: true });
|
||||||
|
const w = dom.window;
|
||||||
|
w.fetch = ((input: string | URL, init?: RequestInit) => fetch(new URL(String(input), node), init)) as unknown as typeof w.fetch;
|
||||||
|
w.scrollTo = () => {};
|
||||||
|
w.eval(bundle);
|
||||||
|
return {
|
||||||
|
w,
|
||||||
|
d: w.document,
|
||||||
|
async waitFor(pred, what, ms = 30000) {
|
||||||
|
const end = Date.now() + ms;
|
||||||
|
while (Date.now() < end) {
|
||||||
|
if (pred()) return;
|
||||||
|
await new Promise((r) => setTimeout(r, 25));
|
||||||
|
}
|
||||||
|
throw new Error(`timed out waiting for: ${what}\n${w.document.body.textContent?.slice(0, 500)}`);
|
||||||
|
},
|
||||||
|
close: () => w.close(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const ok = (what: string) => console.log(`OK ${what}`);
|
||||||
|
const fail = (what: string): never => {
|
||||||
|
throw new Error(what);
|
||||||
|
};
|
||||||
|
const text = (p: Page) => p.d.body.textContent ?? "";
|
||||||
|
const q = <T extends Element = HTMLElement>(p: Page, sel: string) => p.d.querySelector<T>(sel);
|
||||||
|
const qa = (p: Page, sel: string) => [...p.d.querySelectorAll(sel)];
|
||||||
|
const submit = (p: Page, sel: string) => q(p, sel)!.dispatchEvent(new p.w.Event("submit", { cancelable: true, bubbles: true }));
|
||||||
|
const click = (el: Element | null | undefined) => (el as HTMLElement | undefined)?.click();
|
||||||
|
|
||||||
|
async function regions(node: string, token: string): Promise<void> {
|
||||||
|
const status = async () => ((await (await fetch(`${node}/api/v1/status`)).json()) as { regions: string[] }).regions;
|
||||||
|
if ((await status()).length !== 0) fail("the node must start without a region");
|
||||||
|
|
||||||
|
// A visitor is told that the node follows nothing.
|
||||||
|
const visitor = open(node, "#/");
|
||||||
|
await visitor.waitFor(() => /follows no region yet/.test(text(visitor)), "the notice for visitors");
|
||||||
|
ok("a visitor is told the node follows no region yet");
|
||||||
|
visitor.close();
|
||||||
|
|
||||||
|
// The owner signs in with the link the node printed and lands on the picker.
|
||||||
|
const p = open(node, `#/login/${token}`);
|
||||||
|
await p.waitFor(() => q(p, '[name="place"]') !== null, "the regions page right after signing in");
|
||||||
|
const search = q<HTMLInputElement>(p, '[name="place"]')!;
|
||||||
|
await p.waitFor(() => !search.disabled, "the list of places (served by the node)");
|
||||||
|
ok("signing in leads straight to choosing a region");
|
||||||
|
|
||||||
|
search.value = "bonn";
|
||||||
|
search.dispatchEvent(new p.w.Event("input", { bubbles: true }));
|
||||||
|
await p.waitFor(() => q(p, ".rp-result") !== null, "a result for 'bonn'");
|
||||||
|
click(q(p, ".rp-result"));
|
||||||
|
await p.waitFor(() => /Regions around Bonn/.test(text(p)), "the cells around Bonn");
|
||||||
|
click(qa(p, "button").find((b) => b.textContent === "Add"));
|
||||||
|
await p.waitFor(() => q(p, ".rp-chips")!.textContent!.includes("u1j"), "Bonn's cell among the chosen regions");
|
||||||
|
submit(p, "form");
|
||||||
|
await p.waitFor(() => /Saved/.test(text(p)), "the node confirms");
|
||||||
|
const now = await status();
|
||||||
|
if (now[0] !== "u1j") fail(`the node follows ${now}, want u1j first`);
|
||||||
|
if (!text(p).includes(`regions: ${now.join(", ")}`)) fail("the status line does not show the new regions");
|
||||||
|
ok(`the node follows ${now.join(", ")} now, chosen by place name in the browser`);
|
||||||
|
p.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buyer(buyerNode: string, ownerNode: string, token: string, author: string, id: string): Promise<void> {
|
||||||
|
const question = "Ist die Wohnung noch frei? Ich schreibe aus der Oberfläche.";
|
||||||
|
const answer = "Ja, noch frei. Besichtigung diese Woche?";
|
||||||
|
|
||||||
|
// The buyer finds the listing on their node, which verifies its signature in the page.
|
||||||
|
const b = open(buyerNode, `#/l/${author}/${id}`);
|
||||||
|
await b.waitFor(() => q(b, 'textarea[name="message"]') !== null, "the contact form on the listing page");
|
||||||
|
ok("the listing page verified the listing and offers to write to the owner");
|
||||||
|
q<HTMLTextAreaElement>(b, 'textarea[name="message"]')!.value = question;
|
||||||
|
submit(b, "form.compose");
|
||||||
|
await b.waitFor(() => b.w.location.hash.startsWith("#/c/"), "the conversation page (the message was mined and accepted)");
|
||||||
|
await b.waitFor(() => qa(b, ".thread li").some((li) => li.textContent!.includes(question)), "the buyer's own message in the thread");
|
||||||
|
ok("the buyer sent an encrypted message from the UI and sees it in the conversation");
|
||||||
|
|
||||||
|
// The owner, in their own page on their own node, finds the request and answers.
|
||||||
|
const o = open(ownerNode, `#/login/${token}`);
|
||||||
|
await o.waitFor(() => qa(o, ".pane-listings .ocard").length >= 1, "the owner's listings");
|
||||||
|
o.w.location.hash = `#/mine/${id}`;
|
||||||
|
await o.waitFor(() => qa(o, ".pane-requests .ocard").length >= 1, "the request for the listing (it travelled through the network)");
|
||||||
|
ok("the owner's page lists the request");
|
||||||
|
// The listing may have several conversations: open them until the buyer's is there.
|
||||||
|
const hasQuestion = () => qa(o, ".pane-thread .msg").some((m) => m.textContent!.includes(question));
|
||||||
|
for (const end = Date.now() + 30000; !hasQuestion(); ) {
|
||||||
|
if (Date.now() > end) fail("the buyer's text never showed in a conversation of the owner's page");
|
||||||
|
for (let i = 0; i < qa(o, ".pane-requests .ocard").length && !hasQuestion(); i++) {
|
||||||
|
click(qa(o, ".pane-requests .ocard")[i]);
|
||||||
|
await o.waitFor(hasQuestion, "", 1500).catch(() => {}); // not this one: try the next
|
||||||
|
}
|
||||||
|
await new Promise((r) => setTimeout(r, 300)); // the message may still be on its way
|
||||||
|
}
|
||||||
|
ok("the owner reads the buyer's text");
|
||||||
|
q<HTMLTextAreaElement>(o, '.pane-thread textarea[name="reply"]')!.value = answer;
|
||||||
|
submit(o, ".pane-thread form");
|
||||||
|
await o.waitFor(() => qa(o, ".pane-thread .msg.out").some((m) => m.textContent!.includes(answer)), "the owner's reply in the thread");
|
||||||
|
ok("the owner answered from the UI");
|
||||||
|
|
||||||
|
// The buyer's open page polls its mailbox and shows the answer, verified.
|
||||||
|
await b.waitFor(() => qa(b, ".thread li").some((li) => li.textContent!.includes(answer)), "the owner's answer on the buyer's page");
|
||||||
|
const li = qa(b, ".thread li").find((x) => x.textContent!.includes(answer))!;
|
||||||
|
if (!li.textContent!.includes("verified")) fail(`the answer is not marked as verified: ${li.textContent}`);
|
||||||
|
ok("the buyer's page shows the answer, signature verified");
|
||||||
|
b.close();
|
||||||
|
o.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
const [cmd, ...args] = process.argv.slice(2);
|
||||||
|
// The place list is served by the node, so the page needs nothing from disk but the bundle.
|
||||||
|
void places;
|
||||||
|
try {
|
||||||
|
if (cmd === "regions") await regions(args[0]!, args[1]!);
|
||||||
|
else if (cmd === "buyer") await buyer(args[0]!, args[1]!, args[2]!, args[3]!, args[4]!);
|
||||||
|
else fail(`unknown scenario ${cmd}`);
|
||||||
|
process.exit(0);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`FAIL ${(e as Error).message}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user