Files
beacon-server/db/crossings_integration_test.go

241 lines
11 KiB
Go

// Copyright 2026 Beacon Contributors
// SPDX-License-Identifier: AGPL-3.0-or-later
package db
import (
"context"
"os"
"strings"
"testing"
"time"
"github.com/MeshCore-Beacon/beacon-server/internal/api"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
// crossingFixture is two areas either side of a pass, four repeaters on the way across, and one
// observer in each area plus one that rides in a car.
type crossingFixture struct {
passWest, lonely uuid.UUID
}
func seedCrossings(t *testing.T, ctx context.Context, pool *pgxpool.Pool) crossingFixture {
t.Helper()
exec := func(sql string, args ...any) {
t.Helper()
if _, err := pool.Exec(ctx, sql, args...); err != nil {
t.Fatalf("%s: %v", sql, err)
}
}
exec(`INSERT INTO iata_codes (iata, approx_lat, approx_lng) VALUES ('SEA',47.45,-122.31),('YKM',46.57,-120.54),('JFK',40.64,-73.78)`)
key := func(b ...byte) []byte { k := make([]byte, 32); copy(k, b); return k }
node := func(name string, k []byte, lat, lon float64, iatas ...string) uuid.UUID {
id := uuid.New()
exec(`INSERT INTO nodes (id, public_key, name, node_type, latitude, longitude) VALUES ($1,$2,$3,2,$4,$5)`, id, k, name, lat, lon)
for _, c := range iatas {
exec(`INSERT INTO node_short_ids (node_id, iata, prefix_4) VALUES ($1,$2,$3)`, id, c, k[:4])
exec(`INSERT INTO node_iatas (node_id, iata, first_heard, last_heard, observation_count) VALUES ($1,$2,now(),now(),1)`, id, c)
}
return id
}
var f crossingFixture
hA1, hA2, hB1, hB2 := []byte{0xa1, 1, 1}, []byte{0xa2, 2, 2}, []byte{0xb1, 1, 1}, []byte{0xb2, 2, 2}
node("West Hub", key(0xa1, 1, 1, 1), 47.6, -122.3, "SEA")
f.passWest = node("Pass West", key(0xa2, 2, 2, 2), 47.65, -122.3, "SEA", "YKM", "JFK")
node("Pass East", key(0xb1, 1, 1, 1), 46.65, -120.5, "YKM", "SEA")
node("East Hub", key(0xb2, 2, 2, 2), 46.6, -120.5, "YKM")
// Same three bytes as Pass West but a continent away: not a rival, and never matched to a hop.
node("Ohio twin", key(0xa2, 2, 2, 9), 40, -83, "SEA")
// Same first byte and next door: Pass West's one-byte hash is not its own.
node("One byte twin", key(0xa2, 7, 7, 7), 47.7, -122.2, "SEA")
// Shares its whole prefix with a neighbour, so nothing can be counted for it.
f.lonely = node("Lonely", key(0xc3, 3, 3, 3), 47.5, -122.3, "SEA")
node("Lonely twin", key(0xc3, 3, 3, 3, 9), 47.5, -122.2, "SEA")
observer := func(name string, k []byte, iata string, lat, lon float64) uuid.UUID {
id := uuid.New()
exec(`INSERT INTO observers (id, public_key, display_name, last_iata) VALUES ($1,$2,$3,$4)`, id, k, name, iata)
exec(`INSERT INTO nodes (public_key, name, node_type, latitude, longitude) VALUES ($1,$2,1,$3,$4)`, k, name, lat, lon)
return id
}
sea := observer("sea-obs", key(1, 1), "SEA", 47.6, -122.3)
ykm := observer("ykm-obs", key(2, 2), "YKM", 46.6, -120.5)
car := observer("car-obs", key(3, 3), "YKM", 30, -100)
exec(`INSERT INTO meshmapper_repeater_sources (source, url, attempted_at, next_attempt, checked_at) VALUES ('s','u',now(),now(),now())`)
exec(`INSERT INTO meshmapper_repeaters (source, public_key, data) VALUES ('s',$1,'{"carpeater":true}')`, key(3, 3))
type heard struct {
iata string
who uuid.UUID
hops int
path []byte
}
cat := func(h ...[]byte) []byte {
var out []byte
for _, x := range h {
out = append(out, x...)
}
return out
}
packet := func(n byte, payload int, at time.Time, list ...heard) {
h := []byte{n, n, n, n}
exec(`INSERT INTO packets (packet_hash, payload_type, payload_version, route_type, raw_payload, raw_header, first_heard_at, last_heard_at) VALUES ($1,$2,0,1,'\x00','\x00',$3,$3)`, h, payload, at)
seen := map[string]bool{}
for _, x := range list {
if !seen[x.iata] {
seen[x.iata] = true
exec(`INSERT INTO packet_sites (packet_hash, iata, site_heard_at, first_heard_at, payload_type, route_type) VALUES ($1,$2,$3,$3,$4,1)`, h, x.iata, at, payload)
}
exec(`INSERT INTO packet_observations (packet_hash, observer_id, iata, heard_at, path_length_byte, hash_size, hop_count, path_bytes, payload_type) VALUES ($1,$2,$3,$4,0,3,$5,$6,$7)`,
h, x.who, x.iata, at, x.hops, x.path, payload)
}
}
at := time.Now().Add(-time.Hour)
packet(1, 2, at, heard{"SEA", sea, 1, cat(hA1)}, heard{"YKM", ykm, 4, cat(hA1, hA2, hB1, hB2)}, heard{"YKM", car, 3, cat(hA1, hA2, hB1)})
packet(2, 2, at, heard{"SEA", sea, 0, nil}, heard{"YKM", ykm, 3, cat(hA2, hB1, hB2)}, heard{"JFK", car, 9, cat(hA2, hB1, hB2, hB2, hB2, hB2, hB2, hB2, hB2)})
packet(3, 2, at, heard{"YKM", ykm, 0, nil}, heard{"SEA", sea, 3, cat(hB2, hB1, hA2)})
packet(4, 2, at, heard{"SEA", sea, 2, cat(hA1, hA2)}, heard{"YKM", ykm, 2, cat(hB1, hB2)})
// A trace keeps SNR bytes in its path: never read as hops.
packet(5, 9, at, heard{"SEA", sea, 3, cat(hA2, hA2, hA2)}, heard{"YKM", ykm, 1, cat(hA2)})
// Two days old: outside a 24 hour window, inside a 72 hour one.
packet(6, 2, time.Now().Add(-48*time.Hour), heard{"SEA", sea, 0, nil}, heard{"YKM", ykm, 2, cat(hA2, hB1)})
return f
}
func TestCrossingsAndReachPostgres(t *testing.T) {
ctx, pool := schemaPool(t)
if err := RunMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
f := seedCrossings(t, ctx, pool)
s := New(pool, pool, time.Minute, time.Hour)
c, err := s.AnalyzeCrossings(ctx, api.CrossingQuery{SideA: []string{"SEA"}, SideB: []string{"YKM"}, Hours: 24})
if err != nil {
t.Fatal(err)
}
if c.CrossingPackets != 4 || c.AToB != 2 || c.BToA != 1 || c.UnclearDirection != 1 || c.PathsRead != 4 || c.HopsMatchedShare != 1 ||
c.PacketsWithMatchedPaths != 3 || c.PacketsWithCrossingStepSeen != 3 {
t.Fatalf("funnel: %+v", c)
}
if len(c.CrossingPoints) != 2 || c.CrossingPoints[0].Name != "Pass East" || c.CrossingPoints[0].Packets != 2 || c.CrossingPoints[0].Share != 0.667 {
t.Errorf("crossing points: %+v", c.CrossingPoints)
}
if len(c.Bridges) != 2 || c.Bridges[0].From.Name != "Pass West" || c.Bridges[0].To.Name != "Pass East" || c.Bridges[0].Km == nil {
t.Errorf("bridges: %+v", c.Bridges)
}
for _, r := range c.Repeaters {
if (r.Name == "Pass West" && r.Side != "A") || (r.Name == "Pass East" && r.Side != "B") || strings.Contains(r.Name, "twin") {
t.Errorf("repeater: %+v", r)
}
}
if c.Map == nil || len(c.Map.Links) != 3 || !c.Map.Links[0].Crossing {
t.Errorf("map: %+v", c.Map)
}
if wide, err := s.AnalyzeCrossings(ctx, api.CrossingQuery{SideA: []string{"SEA"}, SideB: []string{"YKM"}, Hours: 72}); err != nil || wide.CrossingPackets != 5 {
t.Errorf("72 hours: %+v %v", wide, err)
}
if none, err := s.AnalyzeCrossings(ctx, api.CrossingQuery{SideA: []string{"YKM"}, SideB: []string{"ZZZ"}, Hours: 24}); err != nil || none.CrossingPackets != 0 || len(none.Notes) != 2 {
t.Errorf("nothing crossed: %+v %v", none, err)
}
// JFK was only heard by the car, which places nothing: the repeaters are counted, no bridge is claimed.
unplaced, err := s.AnalyzeCrossings(ctx, api.CrossingQuery{SideA: []string{"SEA"}, SideB: []string{"JFK"}, Hours: 24})
if err != nil || unplaced.CrossingPackets != 1 || len(unplaced.Bridges) != 0 || len(unplaced.Repeaters) != 2 ||
!strings.Contains(strings.Join(unplaced.Notes, " "), "could not be told apart") {
t.Errorf("unplaced side: %+v %v", unplaced, err)
}
r, err := s.GetNodeReach(ctx, api.NodeReachQuery{NodeID: f.passWest, Hours: 24})
if err != nil {
t.Fatal(err)
}
// Packet 2 is the only one whose first hop is Pass West: heard near Yakima and, by the car, in JFK.
if len(r.HashSizesUsed) != 2 || r.HashSizesUsed[0] != 2 || r.Packets != 1 || r.Hearings != 2 {
t.Fatalf("reach: %+v", r)
}
if len(r.Areas) != 2 || len(r.Directions) != 1 || r.Directions[0].Direction != "SE" || r.Directions[0].Observer.Name != "ykm-obs" ||
r.Directions[0].Observer.MinHops != 3 || r.FarthestKm == nil || *r.FarthestKm < 170 {
t.Errorf("reach places: %+v", r)
}
for _, a := range r.Areas {
if (a.IATA == "JFK") != (a.Km == nil) {
t.Errorf("only an area with a fixed observer has a distance: %+v", a)
}
}
if since := time.UnixMilli(r.Since); !since.Equal(since.Truncate(time.Hour)) {
t.Errorf("the window does not start on the hour: %v", since)
}
if wide, err := s.GetNodeReach(ctx, api.NodeReachQuery{NodeID: f.passWest, Hours: 72}); err != nil || wide.Packets != 2 {
t.Errorf("72 hours: %+v %v", wide, err)
}
if near, err := s.GetNodeReach(ctx, api.NodeReachQuery{NodeID: f.passWest, Hours: 24, MaxHops: 2}); err != nil || near.Packets != 0 {
t.Errorf("two hops: %+v %v", near, err)
}
shared, err := s.GetNodeReach(ctx, api.NodeReachQuery{NodeID: f.lonely, Hours: 24})
if err != nil || len(shared.HashSizesUsed) != 0 || shared.Packets != 0 || !strings.Contains(strings.Join(shared.Notes, " "), "shares its path hash") {
t.Errorf("shared hash: %+v %v", shared, err)
}
if unknown, err := s.GetNodeReach(ctx, api.NodeReachQuery{NodeID: uuid.New(), Hours: 24}); unknown != nil || err != nil {
t.Errorf("unknown node: %v %v", unknown, err)
}
}
// The reach search must be answerable from idx_observations_first_hop: its filters have to match the
// index's expressions and predicate exactly, or the planner falls back to reading the whole table.
func TestReachSearchUsesTheFirstHopIndexPostgres(t *testing.T) {
ctx, pool := schemaPool(t)
if err := RunMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
seedCrossings(t, ctx, pool)
tx, err := pool.Begin(ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(ctx)
// The fixture is a handful of rows, where a sequential scan is the cheapest plan.
if _, err := tx.Exec(ctx, "SET LOCAL enable_seqscan = off"); err != nil {
t.Fatal(err)
}
rows, err := tx.Query(ctx, "EXPLAIN "+reachPacketsSQL(t), []time.Time{time.Now().Truncate(time.Hour)}, [][]byte{{0xa2, 2, 2}}, []string{"SEA"}, int32(10))
if err != nil {
t.Fatal(err)
}
var plan strings.Builder
for rows.Next() {
var line string
if err := rows.Scan(&line); err != nil {
t.Fatal(err)
}
plan.WriteString(line + "\n")
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
if !strings.Contains(plan.String(), "idx_observations_first_hop") {
t.Errorf("the reach search does not read idx_observations_first_hop:\n%s", plan.String())
}
}
// reachPacketsSQL is ListReachPackets as written in the query file, with numbered parameters.
func reachPacketsSQL(t *testing.T) string {
t.Helper()
raw, err := os.ReadFile("queries/queries.sql")
if err != nil {
t.Fatal(err)
}
_, sql, ok := strings.Cut(string(raw), "-- name: ListReachPackets :many\n")
if !ok {
t.Fatal("ListReachPackets is not in the query file")
}
sql, _, _ = strings.Cut(sql, ";")
for i, name := range []string{"@hours", "@first_hops", "@iatas", "@max_rows"} {
if !strings.Contains(sql, name) {
t.Fatalf("ListReachPackets has no %s", name)
}
sql = strings.ReplaceAll(sql, name, "$"+string(rune('1'+i)))
}
return sql
}