// Copyright 2026 Beacon Contributors // SPDX-License-Identifier: AGPL-3.0-or-later package db import ( "context" "errors" "fmt" "log/slog" "sort" "time" sqlc "github.com/MeshCore-Beacon/beacon-server/db/sqlc" "github.com/MeshCore-Beacon/beacon-server/internal/api" "github.com/MeshCore-Beacon/beacon-server/internal/crossings" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" ) const ( reachMaxPackets = 5000 // newest packets that started through the node reachMaxObservations = 200000 // reports of them reachMaxRivals = 4000 ) // reachAreas lists the areas within reach of the node: its first-hop packets are heard there by // any observer that did not hear the sender itself. own are the areas the node is listed in, which // are placed by their observers when they have no position of their own. Far areas are left out: // the node may be listed there because an advert was relayed, and another relay there may use // the same hash. func (s *Store) reachAreas(ctx context.Context, node crossings.Node, own []string) ([]string, error) { centres := map[string]crossings.Point{} rows, err := s.q.ListPlacedIATACentres(ctx) if err != nil { return nil, err } for _, r := range rows { if r.ApproxLat != nil && r.ApproxLng != nil && crossings.Valid(*r.ApproxLat, *r.ApproxLng) { centres[r.Iata] = crossings.Point{Lat: *r.ApproxLat, Lon: *r.ApproxLng} } } var missing []string for _, c := range own { if _, ok := centres[c]; !ok { missing = append(missing, c) } } if len(missing) > 0 { obs, err := s.q.ListAreaObserverPositions(ctx, sqlc.ListAreaObserverPositionsParams{Iatas: missing, MaxRows: carrierMaxCandidates}) if err != nil { return nil, err } lat, lon := map[string][]float64{}, map[string][]float64{} for _, o := range obs { if o.Iata != nil && o.Latitude != nil && o.Longitude != nil && crossings.Valid(*o.Latitude, *o.Longitude) { lat[*o.Iata], lon[*o.Iata] = append(lat[*o.Iata], *o.Latitude), append(lon[*o.Iata], *o.Longitude) } } for c := range lat { sort.Float64s(lat[c]) sort.Float64s(lon[c]) centres[c] = crossings.Point{Lat: lat[c][len(lat[c])/2], Lon: lon[c][len(lon[c])/2]} } } var out []string for c, p := range centres { if crossings.DistanceKm(node.Pos, p) <= crossings.MaxFromAreaKm { out = append(out, c) } } sort.Strings(out) return out, nil } // GetNodeReach implements [api.Reader]. func (s *Store) GetNodeReach(ctx context.Context, q api.NodeReachQuery) (*api.NodeReach, error) { row, err := s.q.GetReachNode(ctx, q.NodeID) if errors.Is(err, pgx.ErrNoRows) { return nil, nil } if err != nil { return nil, err } prefix := row.PublicKey if len(prefix) > 4 { prefix = prefix[:4] } node := crossingNode(row.ID, row.Name, row.NodeType, prefix, row.Latitude, row.Longitude) if !node.Located { return nil, api.ErrNodeWithoutPosition } started := time.Now() until := started.UTC().Truncate(time.Second) // The search reads whole hours, so the window starts on the hour. since := until.Add(-time.Duration(q.Hours) * time.Hour).Truncate(time.Hour) in := crossings.ReachInput{Node: node, Since: since, Until: until, MaxHops: q.MaxHops} if len(prefix) == 0 { return crossings.Reach(in), nil } home, err := s.reachAreas(ctx, node, row.Iatas) if err != nil { return nil, err } if len(home) == 0 { in.Notes = append(in.Notes, "No area with a known position lies within 300 km of this node, so there is nowhere to look for its packets.") return crossings.Reach(in), nil } found, err := s.q.ListReachRivals(ctx, sqlc.ListReachRivalsParams{Iatas: home, FirstByte: prefix[:1], ID: node.ID, MaxRows: reachMaxRivals}) if err != nil { return nil, err } rivals := make([]crossings.Node, len(found)) for i, r := range found { rivals[i] = crossingNode(r.ID, nil, 0, r.Prefix4, r.Latitude, r.Longitude) } in.Sizes = crossings.UsableSizes(node, rivals) if len(in.Sizes) == 0 { in.Notes = append(in.Notes, crossings.NoteReachShared) return crossings.Reach(in), nil } firstHops := make([][]byte, len(in.Sizes)) for i, size := range in.Sizes { firstHops[i] = prefix[:size] } setupAt := time.Now() var hours []pgtype.Timestamptz for h := since; !h.After(until); h = h.Add(time.Hour) { hours = append(hours, pgtype.Timestamptz{Time: h, Valid: true}) } hashes, err := s.q.ListReachPackets(ctx, sqlc.ListReachPacketsParams{Hours: hours, FirstHops: firstHops, Iatas: home, MaxRows: reachMaxPackets}) if err != nil { return nil, err } if len(hashes) == reachMaxPackets { in.Notes = append(in.Notes, fmt.Sprintf("Only the newest %d packets in the window were read. Use a shorter window for a full count.", reachMaxPackets)) } seedAt := time.Now() if len(hashes) == 0 { slog.InfoContext(ctx, "analysis: reach", "component", "db", "hours", q.Hours, "areas", len(home), "packets", 0, "setup_ms", setupAt.Sub(started).Milliseconds(), "seed_ms", seedAt.Sub(setupAt).Milliseconds(), "total_ms", time.Since(started).Milliseconds()) return crossings.Reach(in), nil } rows, kept, err := readNewest(hashes, reachMaxObservations, func(h [][]byte) ([]sqlc.ListReachObservationsRow, error) { return s.q.ListReachObservations(ctx, sqlc.ListReachObservationsParams{Hashes: h, FirstHops: firstHops, MaxRows: reachMaxObservations + 1}) }) if err != nil { return nil, err } if kept < len(hashes) { in.Notes = append(in.Notes, fmt.Sprintf("These packets were heard so widely that only the newest %d could be read.", kept)) } observers := map[uuid.UUID]bool{} in.Rows = make([]crossings.Observation, len(rows)) for i, r := range rows { in.Rows[i] = crossings.Observation{Packet: string(r.PacketHash), IATA: r.Iata, HashSize: int(r.HashSize), HopCount: int(r.HopCount), Path: r.PathBytes, Observer: r.ObserverID} observers[r.ObserverID] = true } if in.Observers, err = s.observerPlaces(ctx, observers); err != nil { return nil, err } out := crossings.Reach(in) slog.InfoContext(ctx, "analysis: reach", "component", "db", "hours", q.Hours, "areas", len(home), "packets", kept, "rows", len(rows), "setup_ms", setupAt.Sub(started).Milliseconds(), "seed_ms", seedAt.Sub(setupAt).Milliseconds(), "rows_ms", time.Since(seedAt).Milliseconds(), "total_ms", time.Since(started).Milliseconds()) return out, nil }