diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index c020c1000..44e8d17f1 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -217,6 +217,12 @@ jobs: go test ./... echo "--- Decrypt CLI tests passed ---" + - name: Test path watch module + run: | + set -e -o pipefail + cd internal/pathwatch && go test -race ./... + echo "--- pathwatch tests passed ---" + - name: Test user-management modules (users, mailer) run: | set -e -o pipefail @@ -575,6 +581,8 @@ jobs: suite 2 test-filter-ux-e2e.js BASE_URL=$B suite 1 test-channel-issue-1087-e2e.js BASE_URL=$B suite 1 test-channel-issue-1111-e2e.js BASE_URL=$B + suite 2 test-map-areas-overlay-e2e.js BASE_URL=$B + suite 2 test-packets-origin-e2e.js BASE_URL=$B suite 2 test-map-modal-fluid-e2e.js BASE_URL=$B suite 2 test-map-nodes-pagination-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-observer-iata-1188-e2e.js BASE_URL=$B @@ -688,6 +696,9 @@ jobs: suite 3 test-packets-scope-column.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-path-inspector-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-pr-1490-live-map-gpu-animations-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B + suite 1 test-region-quick-picks.js + suite 3 test-data-tab.js + suite 3 test-data-watch.js suite 3 test-table-sort.js suite 1 test-touch-targets.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-live-dedup.js BASE_URL=$B diff --git a/Dockerfile b/Dockerfile index 76514d2a9..efba1946e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -56,6 +56,10 @@ ENV CC=zigcc CGO_ENABLED=1 # Build server WORKDIR /build/server COPY cmd/server/go.mod cmd/server/go.sum ./ +COPY internal/areamap/ ../../internal/areamap/ +COPY internal/origin/ ../../internal/origin/ +COPY internal/dataindex/ ../../internal/dataindex/ +COPY internal/pathwatch/ ../../internal/pathwatch/ COPY internal/geofilter/ ../../internal/geofilter/ COPY internal/sigvalidate/ ../../internal/sigvalidate/ COPY internal/packetpath/ ../../internal/packetpath/ diff --git a/MIGRATIONS.md b/MIGRATIONS.md index 6bbc857ef..3bd185c3d 100644 --- a/MIGRATIONS.md +++ b/MIGRATIONS.md @@ -29,9 +29,12 @@ if err := s.RunAsyncMigration(ctx, "my_migration_v1", table **immediately** — the ingestor boots and starts ingesting. - `fn` runs in a goroutine; the WaitGroup is shared with the rest of the ingestor (`Store.WaitForAsyncMigrations()` waits for everything). -- On success the row flips to `done`; on error/panic to `failed` with the - error message captured. -- Idempotent: rows in `done` state short-circuit; `failed`/`pending_async` +- On success the row flips to `done`. A returned error matching + `context.Canceled` (including a wrapped error) becomes `cancelled`, such + as when shutdown interrupts a backfill. Other errors, including deadline + expiry, and panics become `failed` even if the context was cancelled. + Both interrupted states retain the error message and completion time. +- Idempotent: rows in `done` state short-circuit; `failed`/`cancelled`/`pending_async` rows are retried on the next boot. Reference implementations: `Store.BackfillPathJSONAsync` (path_json @@ -91,7 +94,7 @@ What this means for async migrations: running against the same DB is not a supported deployment shape. - **Within a single process**, concurrent `RunAsyncMigration(name=X)` callers race the initial `SELECT status` → `UPDATE/INSERT` step. The - current implementation re-schedules `fn` on a pending/failed row so a + current implementation re-schedules `fn` on a pending/failed/cancelled row so a duplicate caller may legitimately re-run it; once status is `done` all further calls short-circuit. See `TestRunAsyncMigration_ConcurrentSameNameSerialized` for the contract. diff --git a/cmd/ingestor/async_migration.go b/cmd/ingestor/async_migration.go index 32133db4e..6b10501ee 100644 --- a/cmd/ingestor/async_migration.go +++ b/cmd/ingestor/async_migration.go @@ -14,8 +14,8 @@ // 1. Run via Store.RunAsyncMigration(...) below (preferred for backfills // and any work that may touch >1K rows). The migration is recorded as // `pending_async` immediately, returns to the caller (boot proceeds), -// and completes in a goroutine. Status flips to `done` (or `failed` -// with an error message) when fn returns. +// and completes in a goroutine. Status flips to `done`, `cancelled`, +// or `failed` when fn returns; interruptions retain the error message. // 2. Carry the preflight annotation comment immediately above the // migration block, e.g. // // PREFLIGHT: async=true reason="" @@ -32,6 +32,7 @@ package main import ( "context" "database/sql" + "errors" "fmt" "log" ) @@ -42,7 +43,7 @@ func ensureAsyncMigrationsTable(db *sql.DB) error { _, err := db.Exec(` CREATE TABLE IF NOT EXISTS _async_migrations ( name TEXT PRIMARY KEY, - status TEXT NOT NULL, -- pending_async | done | failed + status TEXT NOT NULL, -- pending_async | done | cancelled | failed started_at TEXT NOT NULL DEFAULT (datetime('now')), ended_at TEXT, error TEXT @@ -57,10 +58,11 @@ func ensureAsyncMigrationsTable(db *sql.DB) error { // // Contract (pinned by async_migration_test.go): // - status is `pending_async` IMMEDIATELY after this returns. -// - fn runs in a goroutine; on success status becomes `done`, on error or -// panic status becomes `failed` and the error is recorded. +// - fn runs in a goroutine; on success status becomes `done`. Errors matching +// context.Canceled become `cancelled`; other errors and panics become +// `failed`. Both interrupted states record the error and completion time. // - Idempotent: if a row with the same name already exists in `done` -// state, fn is NOT re-run. If in `failed` or `pending_async` state, +// state, fn is NOT re-run. If in `failed`, `cancelled`, or `pending_async`, // fn IS re-scheduled (a previous run may have crashed mid-flight). // - The caller's WaitGroup tracks the goroutine so tests/shutdown can // wait via Store.WaitForAsyncMigrations(). @@ -76,7 +78,7 @@ func (s *Store) RunAsyncMigration(ctx context.Context, name string, fn func(cont if existing == "done" { return nil // already complete, nothing to do } - // pending_async or failed → reset and retry. + // pending_async, cancelled, or failed → reset and retry. if _, err := s.db.Exec(` UPDATE _async_migrations SET status = 'pending_async', started_at = datetime('now'), ended_at = NULL, error = NULL @@ -103,13 +105,17 @@ func (s *Store) RunAsyncMigration(ctx context.Context, name string, fn func(cont log.Printf("[async-migration] %q panic recovered: %v", name, r) } if runErr != nil { + status, label := "failed", "FAILED" + if errors.Is(runErr, context.Canceled) { + status, label = "cancelled", "cancelled" + } if _, err := s.db.Exec(` UPDATE _async_migrations - SET status = 'failed', ended_at = datetime('now'), error = ? - WHERE name = ?`, runErr.Error(), name); err != nil { - log.Printf("[async-migration] failed to record failure for %q: %v", name, err) + SET status = ?, ended_at = datetime('now'), error = ? + WHERE name = ?`, status, runErr.Error(), name); err != nil { + log.Printf("[async-migration] failed to record %s for %q: %v", status, name, err) } - log.Printf("[async-migration] %q FAILED: %v", name, runErr) + log.Printf("[async-migration] %q %s: %v", name, label, runErr) return } if _, err := s.db.Exec(` @@ -129,7 +135,7 @@ func (s *Store) RunAsyncMigration(ctx context.Context, name string, fn func(cont } // AsyncMigrationStatus returns the current status of an async migration -// (one of "pending_async", "done", "failed") or sql.ErrNoRows if no such +// (one of "pending_async", "done", "cancelled", "failed") or sql.ErrNoRows if no such // migration has been registered. func (s *Store) AsyncMigrationStatus(name string) (string, error) { if err := ensureAsyncMigrationsTable(s.db); err != nil { diff --git a/cmd/ingestor/async_migration_test.go b/cmd/ingestor/async_migration_test.go index 2a8a942d2..75974778f 100644 --- a/cmd/ingestor/async_migration_test.go +++ b/cmd/ingestor/async_migration_test.go @@ -1,9 +1,12 @@ package main import ( + "bytes" "context" "database/sql" "fmt" + "log" + "strings" "sync" "sync/atomic" "testing" @@ -149,43 +152,49 @@ func TestRunAsyncMigration_IdempotentSecondCallNoOps(t *testing.T) { } } -// TestRunAsyncMigration_RestartSafetyFailedIsRetried simulates a crashed -// previous run: a row exists in `failed` state from a prior boot. The next -// RunAsyncMigration call MUST re-schedule fn (reset to pending_async, then -// run it), not leave the migration stuck in `failed` forever. -func TestRunAsyncMigration_RestartSafetyFailedIsRetried(t *testing.T) { - s := newTestStore(t) - const name = "test_restart_failed_v1" - - if err := ensureAsyncMigrationsTable(s.db); err != nil { - t.Fatalf("ensure table: %v", err) - } - if _, err := s.db.Exec(`INSERT INTO _async_migrations (name, status, error) VALUES (?, 'failed', 'simulated prior crash')`, name); err != nil { - t.Fatalf("seed failed row: %v", err) - } - - var calls int32 - if err := s.RunAsyncMigration(context.Background(), name, - func(ctx context.Context, db *sql.DB) error { - atomic.AddInt32(&calls, 1) - return nil - }); err != nil { - t.Fatalf("RunAsyncMigration on failed row: %v", err) - } - s.WaitForAsyncMigrations() - waitForStatus(t, s, name, "done", 2*time.Second) - - if got := atomic.LoadInt32(&calls); got != 1 { - t.Fatalf("fn invoked %d times, want 1 (failed-state row must be retried)", got) - } - - // And the error column must be cleared on success. - var errCol sql.NullString - if err := s.db.QueryRow(`SELECT error FROM _async_migrations WHERE name = ?`, name).Scan(&errCol); err != nil { - t.Fatalf("error col: %v", err) - } - if errCol.Valid && errCol.String != "" { - t.Fatalf("error column not cleared on retry success: %q", errCol.String) +// Failed and cancelled runs are retried, with stale completion details cleared. +func TestRunAsyncMigration_RestartSafetyInterruptedIsRetried(t *testing.T) { + for _, previous := range []string{"failed", "cancelled"} { + t.Run(previous, func(t *testing.T) { + s := newTestStore(t) + const name = "test_restart_interrupted_v1" + if _, err := s.db.Exec(`INSERT INTO _async_migrations (name, status, ended_at, error) VALUES (?, ?, '2026-01-01 00:00:00', 'prior interruption')`, name, previous); err != nil { + t.Fatalf("seed interrupted row: %v", err) + } + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(func() { cancel(); s.WaitForAsyncMigrations() }) + release := make(chan struct{}) + var calls int32 + if err := s.RunAsyncMigration(ctx, name, func(ctx context.Context, db *sql.DB) error { + atomic.AddInt32(&calls, 1) + select { + case <-release: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }); err != nil { + t.Fatalf("RunAsyncMigration on %s row: %v", previous, err) + } + + var status string + var endedAt, errCol sql.NullString + if err := s.db.QueryRow(`SELECT status, ended_at, error FROM _async_migrations WHERE name = ?`, name).Scan(&status, &endedAt, &errCol); err != nil { + t.Fatal(err) + } + if status != "pending_async" || endedAt.Valid || errCol.Valid { + t.Fatalf("retry not reset: status=%q ended_at=%v error=%v", status, endedAt, errCol) + } + close(release) + s.WaitForAsyncMigrations() + if err := s.db.QueryRow(`SELECT status, ended_at, error FROM _async_migrations WHERE name = ?`, name).Scan(&status, &endedAt, &errCol); err != nil { + t.Fatal(err) + } + if status != "done" || !endedAt.Valid || endedAt.String == "" || errCol.Valid || atomic.LoadInt32(&calls) != 1 { + t.Fatalf("retry did not complete once: status=%q ended_at=%v error=%v calls=%d", status, endedAt, errCol, calls) + } + }) } } @@ -220,34 +229,63 @@ func TestRunAsyncMigration_RestartSafetyPendingIsRetried(t *testing.T) { } } -// TestRunAsyncMigration_FnErrorRecorded covers the non-panic failure path: -// fn returns an error → status MUST be "failed" with the error captured. -func TestRunAsyncMigration_FnErrorRecorded(t *testing.T) { - s := newTestStore(t) - const name = "test_fn_error_v1" - - if err := s.RunAsyncMigration(context.Background(), name, - func(ctx context.Context, db *sql.DB) error { - return fmt.Errorf("simulated migration error") - }); err != nil { - t.Fatalf("RunAsyncMigration: %v", err) - } - s.WaitForAsyncMigrations() - - status, err := s.AsyncMigrationStatus(name) - if err != nil { - t.Fatalf("status: %v", err) - } - if status != "failed" { - t.Fatalf("status: got %q, want failed", status) - } - - var errCol sql.NullString - if err := s.db.QueryRow(`SELECT error FROM _async_migrations WHERE name = ?`, name).Scan(&errCol); err != nil { - t.Fatalf("error col: %v", err) - } - if !errCol.Valid || errCol.String == "" { - t.Fatalf("error column empty after fn error") +// Classify the returned error, not ctx.Err(): shutdown must not hide failures. +func TestRunAsyncMigration_CompletionStatus(t *testing.T) { + for _, tt := range []struct { + name string + result error + panic bool + want string + }{ + {"cancelled", context.Canceled, false, "cancelled"}, + {"wrapped cancellation", fmt.Errorf("backfill: %w", context.Canceled), false, "cancelled"}, + {"ordinary error", fmt.Errorf("simulated migration error"), false, "failed"}, + {"deadline exceeded", context.DeadlineExceeded, false, "failed"}, + {"panic", context.Canceled, true, "failed"}, + {"completed", nil, false, "done"}, + } { + t.Run(tt.name, func(t *testing.T) { + s := newTestStore(t) + ctx, cancel := context.WithCancel(context.Background()) + var logs bytes.Buffer + previousOutput := log.Writer() + log.SetOutput(&logs) + t.Cleanup(func() { cancel(); s.WaitForAsyncMigrations(); log.SetOutput(previousOutput) }) + const name = "test_completion_v1" + if err := s.RunAsyncMigration(ctx, name, func(ctx context.Context, db *sql.DB) error { + <-ctx.Done() + if tt.panic { + panic(tt.result) + } + return tt.result + }); err != nil { + t.Fatal(err) + } + cancel() + s.WaitForAsyncMigrations() + + var status string + var endedAt, errCol sql.NullString + if err := s.db.QueryRow(`SELECT status, ended_at, error FROM _async_migrations WHERE name = ?`, name).Scan(&status, &endedAt, &errCol); err != nil { + t.Fatal(err) + } + if status != tt.want || !endedAt.Valid || endedAt.String == "" { + t.Fatalf("completion: status=%q want=%q ended_at=%v", status, tt.want, endedAt) + } + wantErr := "" + if tt.result != nil { + wantErr = tt.result.Error() + } + if tt.panic { + wantErr = "panic: " + wantErr + } + if errCol.Valid != (tt.result != nil) || errCol.String != wantErr { + t.Fatalf("error=%v, want %q", errCol, wantErr) + } + if tt.want == "cancelled" && (strings.Contains(logs.String(), "FAILED") || !strings.Contains(logs.String(), "cancelled")) { + t.Fatalf("cancellation logged as failure: %s", logs.String()) + } + }) } } diff --git a/cmd/ingestor/stats_file_test.go b/cmd/ingestor/stats_file_test.go index e96d56bd1..59d59f0ba 100644 --- a/cmd/ingestor/stats_file_test.go +++ b/cmd/ingestor/stats_file_test.go @@ -2,8 +2,11 @@ package main import ( "encoding/json" + "errors" "os" "path/filepath" + "runtime" + "syscall" "testing" "time" ) @@ -129,6 +132,9 @@ func TestWriteStatsAtomic_SymlinkAtDestIsReplaced(t *testing.T) { // Pre-plant a symlink at the destination path. path := filepath.Join(dir, "stats.json") if err := os.Symlink(target, path); err != nil { + if runtime.GOOS == "windows" && errors.Is(err, syscall.Errno(1314)) { + t.Skip("Windows account cannot create symlinks; this security fixture must run on Linux CI") + } t.Fatalf("symlink: %v", err) } diff --git a/cmd/server/area_filter_test.go b/cmd/server/area_filter_test.go index 25c07d909..d76e4d82c 100644 --- a/cmd/server/area_filter_test.go +++ b/cmd/server/area_filter_test.go @@ -74,7 +74,7 @@ func TestGetNodePubkeysInArea_Polygon(t *testing.T) { } // newTestStoreWithDB builds a minimal PacketStore wired to the given DB and config. -func newTestStoreWithDB(t *testing.T, db *DB, cfg *Config) *PacketStore { +func newTestStoreWithDB(t testing.TB, db *DB, cfg *Config) *PacketStore { t.Helper() return &PacketStore{ db: db, diff --git a/cmd/server/areas.go b/cmd/server/areas.go new file mode 100644 index 000000000..0497dfb23 --- /dev/null +++ b/cmd/server/areas.go @@ -0,0 +1,119 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" + "sort" + "sync" + + "github.com/meshcore-analyzer/areamap" +) + +// LoadAreaMap builds the map of every area: config.json's areas (layer +// "region") and the features of AreasFile. It stores the map on cfg, where +// the store and the handlers find it. A code defined twice, a missing file +// or a file that is not GeoJSON is an error: the caller refuses to start +// rather than run with areas silently missing. +func LoadAreaMap(cfg *Config, configDir string) (*areamap.Map, error) { + var areas []areamap.Area + keys := make([]string, 0, len(cfg.Areas)) + for k := range cfg.Areas { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + e := cfg.Areas[k] + if e.Label == "" { + continue // "_comment" and other non-areas + } + var ring [][2]float64 + switch { + case len(e.Polygon) >= 3: + // config.json polygons are [lat, lon]; GeoJSON rings are [lon, lat]. + for _, p := range e.Polygon { + ring = append(ring, [2]float64{p[1], p[0]}) + } + case e.LatMin != nil && e.LatMax != nil && e.LonMin != nil && e.LonMax != nil: + ring = [][2]float64{{*e.LonMin, *e.LatMin}, {*e.LonMax, *e.LatMin}, {*e.LonMax, *e.LatMax}, {*e.LonMin, *e.LatMax}} + default: + continue // listed by name only, with nothing to locate against + } + areas = append(areas, areamap.Area{Code: k, Label: e.Label, Layer: areamap.DefaultLayer, Polygons: [][][][2]float64{{ring}}}) + } + if cfg.AreasFile != "" { + path := cfg.AreasFile + if !filepath.IsAbs(path) { + path = filepath.Join(configDir, path) + } + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("areasFile: %w", err) + } + fromFile, err := areamap.ParseGeoJSON(data) + if err != nil { + return nil, fmt.Errorf("areasFile %s: %w", path, err) + } + areas = append(areas, fromFile...) + } + m, err := areamap.New(areas) + if err != nil { + return nil, err + } + cfg.areaMap = m + return m, nil +} + +// fileArea reports whether code names an area that only the areas file +// defines, so area= resolves it by position instead of config.json's entry. +func (c *Config) fileArea(code string) bool { + if c == nil || c.areaMap == nil { + return false + } + if _, inConfig := c.Areas[code]; inConfig { + return false + } + return c.areaMap.Has(code) +} + +// areaGeoTolerance is how far, in degrees (about 450 m north-south), a +// drawn outline may stray from the file's: too little to see at regional +// zoom. On a 247 KB, 13,700-point country file it gives 10,400 points and +// 62 KB gzipped, built in under 3 ms. +const areaGeoTolerance = 0.004 + +// areaGeoCache holds each area map's GeoJSON per layer, built on first +// request. Area maps never change after startup, so nothing is evicted. +var areaGeoCache sync.Map // areaGeoKey -> []byte + +type areaGeoKey struct { + m *areamap.Map + layer string +} + +// GET /api/config/areas/geojson[?layer=] +// +// Every area's shape for drawing, from config.json and the areas file alike, +// simplified to areaGeoTolerance. layer picks one layer; none means all. +func (s *Server) handleConfigAreasGeoJSON(w http.ResponseWriter, r *http.Request) { + m := s.cfg.areaMap + if m == nil { + writeJSON(w, areamap.FeatureCollection{Type: "FeatureCollection", Features: []areamap.Feature{}}) + return + } + key := areaGeoKey{m, r.URL.Query().Get("layer")} + body, ok := areaGeoCache.Load(key) + if !ok { + b, err := json.Marshal(m.FeatureCollection(key.layer, areaGeoTolerance)) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + body, _ = areaGeoCache.LoadOrStore(key, b) + } + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "public, max-age=300") + _, _ = w.Write(body.([]byte)) +} diff --git a/cmd/server/areas_test.go b/cmd/server/areas_test.go new file mode 100644 index 000000000..4170db65e --- /dev/null +++ b/cmd/server/areas_test.go @@ -0,0 +1,186 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/gorilla/mux" + "github.com/meshcore-analyzer/areamap" +) + +// A rough Scotland on the "country" layer, in GeoJSON's [lon, lat] order. +const scotlandGeoJSON = `{"type":"FeatureCollection","features":[ + {"type":"Feature","properties":{"code":"SCO","label":"Scotland","layer":"country","iata":["EDI"]}, + "geometry":{"type":"Polygon","coordinates":[[[-7.5,55.0],[-1.5,55.0],[-1.5,60.9],[-7.5,60.9],[-7.5,55.0]]]}}]}` + +func writeAreasFile(t *testing.T, body string) string { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "areas.geojson"), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func belgium() map[string]AreaEntry { + return map[string]AreaEntry{ + "BEL": {Label: "Belgium", Polygon: [][2]float64{{50.0, 2.5}, {51.5, 2.5}, {51.5, 6.4}, {50.0, 6.4}}}, + "_comment": {}, + } +} + +func TestLoadAreaMapReadsConfigAreasAndTheFile(t *testing.T) { + dir := writeAreasFile(t, scotlandGeoJSON) + cfg := &Config{Areas: belgium(), AreasFile: "areas.geojson"} + m, err := LoadAreaMap(cfg, dir) + if err != nil { + t.Fatal(err) + } + if cfg.areaMap != m { + t.Error("the map must be kept on the config for the store and handlers") + } + // config.json polygons are [lat, lon]; they must land the right way round. + if got, _ := m.Locate(areamap.DefaultLayer, 50.85, 4.35); got != "BEL" { + t.Errorf("Brussels = %q, want BEL from config.json", got) + } + if got, _ := m.Locate("country", 55.95, -3.19); got != "SCO" { + t.Errorf("Edinburgh = %q, want SCO from the file", got) + } + if got, _ := m.LocateIATA("country", "edi"); got != "SCO" { + t.Errorf("EDI = %q, want SCO", got) + } +} + +func TestLoadAreaMapRefusesBadFiles(t *testing.T) { + dup := `{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"code":"BEL","label":"Again"},"geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,0]]]}}]}` + cases := map[string]struct { + body, file string + }{ + "a code also in config.json": {dup, "areas.geojson"}, + "a missing file": {scotlandGeoJSON, "nope.geojson"}, + "not GeoJSON": {`{`, "areas.geojson"}, + } + for name, c := range cases { + dir := writeAreasFile(t, c.body) + if _, err := LoadAreaMap(&Config{Areas: belgium(), AreasFile: c.file}, dir); err == nil { + t.Errorf("%s: accepted, want an error", name) + } + } + if m, err := LoadAreaMap(&Config{}, t.TempDir()); err != nil || len(m.Areas("")) != 0 { + t.Errorf("no areas at all = %v, %v; want an empty map and no error", m, err) + } +} + +func TestHandleConfigAreasListsFileAreasWithTheirLayer(t *testing.T) { + dir := writeAreasFile(t, scotlandGeoJSON) + cfg := &Config{Areas: belgium(), AreasFile: "areas.geojson"} + if _, err := LoadAreaMap(cfg, dir); err != nil { + t.Fatal(err) + } + r := mux.NewRouter() + srv := &Server{db: setupTestDBv2(t), cfg: cfg} + r.HandleFunc("/api/config/areas", srv.handleConfigAreas).Methods("GET") + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/config/areas", nil)) + var got []map[string]string + if err := json.NewDecoder(w.Body).Decode(&got); err != nil { + t.Fatal(err) + } + layers := map[string]string{} + for _, a := range got { + layers[a["key"]] = a["layer"] + } + if len(got) != 2 || layers["BEL"] != areamap.DefaultLayer || layers["SCO"] != "country" { + t.Errorf("areas = %v, want BEL (region) and SCO (country)", got) + } +} + +func TestAreaFilterWorksForFileAreas(t *testing.T) { + db := setupTestDBv2(t) + mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('edinburgh', 55.95, -3.19)`) + mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('newcastle', 54.97, -1.61)`) + mustExecDB(t, db, `INSERT INTO nodes (public_key, lat, lon) VALUES ('dublin', 53.35, -6.26)`) + dir := writeAreasFile(t, scotlandGeoJSON) + cfg := &Config{AreasFile: "areas.geojson"} + if _, err := LoadAreaMap(cfg, dir); err != nil { + t.Fatal(err) + } + s := newTestStoreWithDB(t, db, cfg) + got := s.resolveAreaNodes("SCO") + if len(got) != 1 || !got["edinburgh"] { + t.Errorf("nodes in SCO = %v, want only edinburgh", got) + } + // config.json areas keep their own path, unchanged. + cfg.Areas = belgium() + if got := s.resolveAreaNodes("BEL"); got != nil { + t.Errorf("no Belgian nodes, got %v", got) + } +} + +// The example in docs/ must load as documented. +func TestTheDocumentedExampleAreasFileLoads(t *testing.T) { + cfg := &Config{AreasFile: "../../docs/examples/areas.example.geojson"} + m, err := LoadAreaMap(cfg, ".") + if err != nil { + t.Fatal(err) + } + if got, _ := m.Locate(areamap.DefaultLayer, 37.34, -121.89); got != "BAY" { + t.Errorf("San Jose = %q, want BAY", got) + } + if got, _ := m.LocateIATA(areamap.DefaultLayer, "MRY"); got != "MRY" { + t.Errorf("observer MRY = %q, want MRY", got) + } +} + +func TestConfigAreasGeoJSONServesEveryAreaShape(t *testing.T) { + dir := writeAreasFile(t, scotlandGeoJSON) + cfg := &Config{Areas: belgium(), AreasFile: "areas.geojson"} + if _, err := LoadAreaMap(cfg, dir); err != nil { + t.Fatal(err) + } + r := mux.NewRouter() + srv := &Server{db: setupTestDBv2(t), cfg: cfg} + r.HandleFunc("/api/config/areas/geojson", srv.handleConfigAreasGeoJSON).Methods("GET") + get := func(q string) (int, areamap.FeatureCollection, string) { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/config/areas/geojson"+q, nil)) + var fc areamap.FeatureCollection + body := w.Body.String() + _ = json.Unmarshal([]byte(body), &fc) + return w.Code, fc, body + } + code, fc, body := get("") + if code != 200 || fc.Type != "FeatureCollection" || len(fc.Features) != 2 { + t.Fatalf("all areas = %d %s", code, body) + } + byCode := map[string]areamap.Feature{} + for _, f := range fc.Features { + byCode[f.Properties.Code] = f + } + if byCode["BEL"].Properties.Layer != areamap.DefaultLayer || len(byCode["BEL"].Geometry.Coordinates) != 1 { + t.Errorf("config.json's box should come back as a polygon: %+v", byCode["BEL"]) + } + if byCode["SCO"].Properties.Layer != "country" || byCode["SCO"].Properties.Label == "" { + t.Errorf("the file's area should keep its layer and label: %+v", byCode["SCO"].Properties) + } + if _, one, _ := get("?layer=country"); len(one.Features) != 1 || one.Features[0].Properties.Code != "SCO" { + t.Errorf("layer=country = %+v, want SCO only", one.Features) + } + _, _, again := get("") + if again != body { + t.Error("the same request should give the same bytes (built once)") + } + empty := &Server{db: setupTestDBv2(t), cfg: &Config{}} + r2 := mux.NewRouter() + r2.HandleFunc("/api/config/areas/geojson", empty.handleConfigAreasGeoJSON).Methods("GET") + w := httptest.NewRecorder() + r2.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/config/areas/geojson", nil)) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"features":[]`) { + t.Errorf("no areas = %d %s, want an empty FeatureCollection", w.Code, w.Body.String()) + } +} diff --git a/cmd/server/channel_analytics_test.go b/cmd/server/channel_analytics_test.go index b2a44ad25..dfc79b056 100644 --- a/cmd/server/channel_analytics_test.go +++ b/cmd/server/channel_analytics_test.go @@ -27,7 +27,6 @@ func newChannelTestStore(packets []*StoreTx) *PacketStore { chanCache: make(map[string]*cachedResult), distCache: make(map[string]*cachedResult), subpathCache: make(map[string]*cachedResult), - spIndex: make(map[string]int), spTxIndex: make(map[string][]*StoreTx), advertPubkeys: make(map[string]int), clockSkew: NewClockSkewEngine(), diff --git a/cmd/server/config.go b/cmd/server/config.go index 36b90c701..fe8ae4279 100644 --- a/cmd/server/config.go +++ b/cmd/server/config.go @@ -11,6 +11,7 @@ import ( "sync/atomic" "time" + "github.com/meshcore-analyzer/areamap" "github.com/meshcore-analyzer/dbconfig" "github.com/meshcore-analyzer/geofilter" "github.com/meshcore-analyzer/packetpath" @@ -24,6 +25,9 @@ type AreaEntry struct { LatMax *float64 `json:"latMax,omitempty"` LonMin *float64 `json:"lonMin,omitempty"` LonMax *float64 `json:"lonMax,omitempty"` + // match, when set, decides membership instead of the polygon or box: an + // area from areasFile, tested against its GeoJSON geometry. + match func(lat, lon float64) bool } // ListLimitsConfig defines maximum row limits for list endpoints to prevent DoS. @@ -104,6 +108,11 @@ type Config struct { Regions map[string]string `json:"regions"` + // RegionQuickPicks are named groups of region (IATA) codes offered as + // one-tap choices in the region filter, e.g. a country's observers. See + // NormalizedRegionQuickPicks and config.example.json. + RegionQuickPicks []RegionQuickPick `json:"regionQuickPicks,omitempty"` + Roles map[string]interface{} `json:"roles"` HealthThresholds *HealthThresholds `json:"healthThresholds"` PathTrust *PathTrustConfig `json:"pathTrust,omitempty"` @@ -139,6 +148,18 @@ type Config struct { GeoFilter *GeoFilterConfig `json:"geo_filter,omitempty"` Areas map[string]AreaEntry `json:"areas,omitempty"` + // AreasFile names a GeoJSON FeatureCollection of further areas, relative + // to the config directory: real boundaries (coastlines, islands, holes) + // in layers, which config.json's polygons cannot hold. See + // internal/areamap for the feature properties it reads. + AreasFile string `json:"areasFile,omitempty"` + // areaMap holds every area, from Areas and AreasFile, once LoadAreaMap + // has run. Nil until then. + areaMap *areamap.Map + + // Data turns on the Data tab: every packet of the last few days placed + // by the area it started in and the areas that heard it. Needs areas. + Data *DataConfig `json:"data,omitempty"` Timestamps *TimestampConfig `json:"timestamps,omitempty"` @@ -876,6 +897,67 @@ func (c *Config) BlacklistGeneration() uint64 { return c.blacklistGen.Load() } +// RegionQuickPick is one named group of region codes for the region filter. +type RegionQuickPick struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + Regions []string `json:"regions"` +} + +// Limits on the configured quick picks, so a typo in config.json cannot put +// thousands of buttons or codes into every page. +const ( + maxRegionQuickPicks = 20 + maxRegionQuickPickRegions = 200 +) + +// NormalizedRegionQuickPicks returns the configured quick picks, cleaned up: +// names, descriptions and codes trimmed, codes upper-cased and de-duplicated +// in their configured order, picks without a name or any code dropped, and at +// most maxRegionQuickPicks picks of maxRegionQuickPickRegions codes each. +// Never nil, so the API always answers with a list. +func (c *Config) NormalizedRegionQuickPicks() []RegionQuickPick { + out := []RegionQuickPick{} + if c == nil { + return out + } + for _, p := range c.RegionQuickPicks { + if len(out) >= maxRegionQuickPicks { + break + } + name := strings.TrimSpace(p.Name) + if name == "" { + continue + } + codes := normalizeQuickPickCodes(p.Regions) + if len(codes) == 0 { + continue + } + out = append(out, RegionQuickPick{Name: name, Description: strings.TrimSpace(p.Description), Regions: codes}) + } + return out +} + +// normalizeQuickPickCodes trims and upper-cases a pick's codes, drops empty +// and repeated ones in their configured order, and keeps at most +// maxRegionQuickPickRegions. +func normalizeQuickPickCodes(regions []string) []string { + seen := make(map[string]bool, len(regions)) + codes := make([]string, 0, len(regions)) + for _, r := range regions { + code := strings.ToUpper(strings.TrimSpace(r)) + if code == "" || seen[code] { + continue + } + if len(codes) >= maxRegionQuickPickRegions { + break + } + seen[code] = true + codes = append(codes, code) + } + return codes +} + // IsBlacklisted returns true if the given public key is in the nodeBlacklist. // Hot read path: a single atomic pointer load + map lookup. No locks, no // sync.Once. The in-memory set is populated either via SetNodeBlacklist or diff --git a/cmd/server/config_mode_test.go b/cmd/server/config_mode_test.go index 601ef7656..0abb6bfc0 100644 --- a/cmd/server/config_mode_test.go +++ b/cmd/server/config_mode_test.go @@ -3,6 +3,7 @@ package main import ( "os" "path/filepath" + "runtime" "testing" ) @@ -10,6 +11,9 @@ import ( // API key and broker passwords, so the rewrite must keep whatever mode the // operator set rather than resetting it to 0644. func TestSaveGeoFilterPreservesFileMode(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows does not support POSIX file permission bits") + } dir := t.TempDir() path := filepath.Join(dir, "config.json") if err := os.WriteFile(path, []byte(`{"apiKey":"secret-key-that-is-long-enough"}`+"\n"), 0600); err != nil { diff --git a/cmd/server/coverage_test.go b/cmd/server/coverage_test.go index 233c26bd6..fbd2ccb62 100644 --- a/cmd/server/coverage_test.go +++ b/cmd/server/coverage_test.go @@ -2332,8 +2332,8 @@ func TestSubpathPrecomputedIndex(t *testing.T) { } // After Load(), the precomputed index must be populated. - if len(store.spIndex) == 0 { - t.Fatal("expected spIndex to be populated after Load()") + if len(store.spTxIndex) == 0 { + t.Fatal("expected spTxIndex to be populated after Load()") } if store.spTotalPaths == 0 { t.Fatal("expected spTotalPaths > 0 after Load()") @@ -2349,11 +2349,11 @@ func TestSubpathPrecomputedIndex(t *testing.T) { "eeff,0011,2233": 1, } for key, want := range expectedRaw { - got, ok := store.spIndex[key] + txs, ok := store.spTxIndex[key] if !ok { - t.Errorf("expected spIndex[%q] to exist", key) - } else if got != want { - t.Errorf("spIndex[%q] = %d, want %d", key, got, want) + t.Errorf("expected spTxIndex[%q] to exist", key) + } else if got := len(txs); got != want { + t.Errorf("len(spTxIndex[%q]) = %d, want %d", key, got, want) } } if store.spTotalPaths != 3 { @@ -2389,20 +2389,16 @@ func TestSubpathTxIndexPopulated(t *testing.T) { t.Fatal("indexes never became ready") } - // spTxIndex must be populated alongside spIndex + // spTxIndex must be populated after Load() if len(store.spTxIndex) == 0 { t.Fatal("expected spTxIndex to be populated after Load()") } - // Every key in spIndex must also exist in spTxIndex with matching count - for key, count := range store.spIndex { - txs, ok := store.spTxIndex[key] - if !ok { - t.Errorf("spTxIndex missing key %q that exists in spIndex", key) - continue - } - if len(txs) != count { - t.Errorf("spTxIndex[%q] has %d txs, spIndex count is %d", key, len(txs), count) + // len(spTxIndex[key]) is the subpath's count, so no key may be kept + // with an empty transaction list. + for key, txs := range store.spTxIndex { + if len(txs) == 0 { + t.Errorf("spTxIndex[%q] is empty; empty keys must be deleted", key) } } diff --git a/cmd/server/data.go b/cmd/server/data.go new file mode 100644 index 000000000..09d8e9a1b --- /dev/null +++ b/cmd/server/data.go @@ -0,0 +1,777 @@ +package main + +// The Data tab's server side: a compact index of every packet of the last +// data.days days (internal/dataindex), each attributed to the area it started +// in and the areas that heard it (internal/origin), placed by the areas from +// config.json and areasFile (internal/areamap). +// +// The index reads SQLite directly, read-only, the way the packet store's own +// loader does: a background fill at startup, newest first, then every two +// minutes the last half hour is re-derived, because observations keep +// arriving after a packet is first seen. Node positions are re-read every +// half hour and the whole index is rebuilt once a day so moved nodes count +// where they stand now. + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "log" + "math" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/meshcore-analyzer/areamap" + "github.com/meshcore-analyzer/dataindex" + "github.com/meshcore-analyzer/origin" + "golang.org/x/sync/singleflight" +) + +// DataConfig turns on the Data tab and sets how far back it reaches. +type DataConfig struct { + Enabled bool `json:"enabled"` + // Days of history the index holds: default 7, at most 30. Each day costs + // about 0.7 MB per 10,000 packets a day. + Days int `json:"days,omitempty"` + // Layer is the areamap layer the tab places packets in. Default: the + // first layer the areas define. + Layer string `json:"layer,omitempty"` + // HomeArea, when set, names the area whose boundary relays and + // "via home" counts the flows report. + HomeArea string `json:"homeArea,omitempty"` + // DashboardsFile names a JSON file of ready-made dashboards, relative to + // the config directory, offered to every visitor beside the built-in ones. + DashboardsFile string `json:"dashboardsFile,omitempty"` + // DefaultDashboard is the id of the dashboard the tab opens on. + DefaultDashboard string `json:"defaultDashboard,omitempty"` + // PathDays is how far back path watch panels remember (default 21, at + // most 45): a two-week flag needs the fortnight and the week before. + PathDays int `json:"pathDays,omitempty"` +} + +// PathDays is how many days the path watch history holds. +func (c *Config) PathDays() int { + if c == nil || c.Data == nil || c.Data.PathDays <= 0 { + return 21 + } + return min(c.Data.PathDays, 45) +} + +// DataEnabled reports whether the Data tab is switched on. +func (c *Config) DataEnabled() bool { return c != nil && c.Data != nil && c.Data.Enabled } + +// DataDays is how many days the Data index holds. +func (c *Config) DataDays() int { + if c == nil || c.Data == nil || c.Data.Days <= 0 { + return 7 + } + if c.Data.Days > 30 { + return 30 + } + return c.Data.Days +} + +const ( + dataRefreshEvery = 2 * time.Minute + dataRefreshSpan = 30 * time.Minute + dataLocatorEvery = 30 * time.Minute + dataRebuildEvery = 24 * time.Hour + dataCacheFor = 60 * time.Second + dataFillChunk = 2000 + dataPacketSlots = 2 + dataSQLTimeFormat = "2006-01-02T15:04:05.000Z" // the store's own format +) + +type dataCached struct { + at time.Time + body []byte +} + +// dataService owns the index and answers the /api/data endpoints. +type dataService struct { + // firstFill, when set, is closed once the first fill has run. + firstFill chan struct{} + db *DB + areas *areamap.Map + layer string + home string + days int + + now func() time.Time + refreshSpan time.Duration + + mu sync.RWMutex + ix *dataindex.Index + loc *origin.Locator + locAt time.Time + filling bool + // waitFor, when set, holds the first fill until it closes: the packet + // store's startup-load-done signal (see main.go). + waitFor <-chan struct{} + builtAt time.Time + cache map[string]dataCached + sf singleflight.Group + slots chan struct{} + + dashboards *DataDashboards +} + +// newDataService returns nil when the tab is off, and an error when it is on +// but no areas are defined, since nothing could be placed. +func newDataService(db *DB, cfg *Config) (*dataService, error) { + if !cfg.DataEnabled() { + return nil, nil + } + d := &dataService{ + db: db, days: cfg.DataDays(), + now: time.Now, refreshSpan: dataRefreshSpan, + cache: map[string]dataCached{}, slots: make(chan struct{}, dataPacketSlots), + } + if !cfg.hasAreas() { + // No areas: the tab counts by kind, type, channel, scope and routing, + // and every packet starts and is heard in Unknown. + if cfg.Data.HomeArea != "" { + return nil, fmt.Errorf("data.homeArea %q needs areas: set areasFile or areas in config.json", cfg.Data.HomeArea) + } + return d, nil + } + m := cfg.areaMap + layer := cfg.Data.Layer + if layer == "" { + layer = m.Layers()[0] + } + if len(m.Areas(layer)) == 0 { + return nil, fmt.Errorf("data.layer %q has no areas (layers: %v)", layer, m.Layers()) + } + if h := cfg.Data.HomeArea; h != "" && !m.Has(h) { + return nil, fmt.Errorf("data.homeArea %q is not an area", h) + } + d.areas, d.layer, d.home = m, layer, cfg.Data.HomeArea + return d, nil +} + +// hasAreas reports whether config.json or areasFile defines any area, so the +// Data tab can place packets. +func (c *Config) hasAreas() bool { + return c.areaMap != nil && len(c.areaMap.Areas("")) > 0 +} + +// places reports whether the tab places packets in areas. +func (d *dataService) places() bool { return d.areas != nil } + +// dimensions are the filter dimensions that mean something here: all of +// them with areas, none of the place ones without. +func (d *dataService) dimensions() []string { + if d.places() { + return dataindex.Dimensions + } + var out []string + for _, k := range dataindex.Dimensions { + if !dataindex.PlaceDimensions[k] { + out = append(out, k) + } + } + return out +} + +func (d *dataService) areaCodes() []string { + var out []string + if !d.places() { + return out + } + for _, a := range d.areas.Areas(d.layer) { + out = append(out, a.Code) + } + return out +} + +func (d *dataService) index() *dataindex.Index { + d.mu.RLock() + defer d.mu.RUnlock() + return d.ix +} + +func (d *dataService) locator() *origin.Locator { + d.mu.RLock() + defer d.mu.RUnlock() + return d.loc +} + +// run fills the index, then keeps it current until ctx ends. +func (d *dataService) run(ctx context.Context) { + if d.waitFor != nil { + // Never fill on top of the packet store's startup load: together they + // outgrew a 1.5 GB container. Report filling while waiting. + d.mu.Lock() + d.filling = true + d.mu.Unlock() + select { + case <-d.waitFor: + case <-ctx.Done(): + return + } + log.Printf("[data] packet store loaded; filling the index") + } + if err := d.fill(ctx); err != nil { + log.Printf("[data] fill failed: %v", err) + } + if d.firstFill != nil { + close(d.firstFill) // the path watch fills after this one, never alongside + } + tick := time.NewTicker(dataRefreshEvery) + defer tick.Stop() + for { + select { + case <-ctx.Done(): + return + case <-tick.C: + } + var err error + if d.now().Sub(d.builtAt) >= dataRebuildEvery { + err = d.fill(ctx) + } else { + err = d.refresh(ctx) + } + if err != nil { + log.Printf("[data] refresh failed: %v", err) + } + } +} + +// loadLocator reads node and observer positions. +func (d *dataService) loadLocator(ctx context.Context) (*origin.Locator, error) { + var nodes []origin.Node + rows, err := d.db.conn.QueryContext(ctx, `SELECT public_key, COALESCE(name, ''), COALESCE(role, ''), lat, lon FROM nodes`) + if err != nil { + return nil, err + } + for rows.Next() { + var n origin.Node + var role string + var lat, lon sql.NullFloat64 + if err := rows.Scan(&n.PublicKey, &n.Name, &role, &lat, &lon); err != nil { + rows.Close() + return nil, err + } + n.Relay = role == "repeater" || role == "room" + if lat.Valid && lon.Valid { + la, lo := lat.Float64, lon.Float64 + n.Lat, n.Lon = &la, &lo + } + nodes = append(nodes, n) + } + rows.Close() + var obs []origin.Observer + rows, err = d.db.conn.QueryContext(ctx, `SELECT id, COALESCE(iata, '') FROM observers`) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var o origin.Observer + if err := rows.Scan(&o.ID, &o.IATA); err != nil { + return nil, err + } + obs = append(obs, o) + } + if err := rows.Err(); err != nil { + return nil, err + } + return origin.NewLocator(origin.Options{Areas: d.areas, Layer: d.layer, Home: d.home}, nodes, obs), nil +} + +// fill builds a fresh index of the last d.days days, newest chunk first, so +// the recent past is answerable within seconds. The first fill serves its +// index as it grows; later rebuilds swap in when complete. +func (d *dataService) fill(ctx context.Context) error { + start, clock := d.now(), time.Now() + loc, err := d.loadLocator(ctx) + if err != nil { + return err + } + ix := dataindex.New(dataindex.Options{Areas: d.areaCodes(), Home: d.home, NoPlaces: !d.places()}) + since := start.Add(-time.Duration(d.days) * 24 * time.Hour).Truncate(time.Second) + d.mu.Lock() + first := d.ix == nil + d.loc, d.locAt = loc, start + if first { + d.ix, d.filling = ix, true + } + d.mu.Unlock() + defer func() { + d.mu.Lock() + d.filling = false + d.mu.Unlock() + }() + + var lo, hi sql.NullInt64 + if err := d.db.conn.QueryRowContext(ctx, `SELECT MIN(id), MAX(id) FROM transmissions WHERE first_seen >= ?`, + since.UTC().Format(dataSQLTimeFormat)).Scan(&lo, &hi); err != nil { + return err + } + n := 0 + if lo.Valid { + for b := hi.Int64; b >= lo.Int64; b -= dataFillChunk { + a := b - dataFillChunk + 1 + if a < lo.Int64 { + a = lo.Int64 + } + pkts, err := d.readPackets(ctx, "t.id BETWEEN ? AND ? AND t.first_seen >= ?", a, b, since.UTC().Format(dataSQLTimeFormat)) + if err != nil { + return err + } + recs := make([]origin.Record, len(pkts)) + oldest := int64(math.MaxInt64) + for i := range pkts { + recs[i] = loc.Derive(pkts[i]) + if recs[i].At < oldest { + oldest = recs[i].At + } + } + ix.Replace(math.MaxInt64, recs) + n += len(recs) + if first && oldest != math.MaxInt64 { + ix.SetCovered(oldest) + } + if err := ctx.Err(); err != nil { + return err + } + } + } + ix.SetCovered(since.Unix()) + d.mu.Lock() + d.ix, d.builtAt = ix, start + d.cache = map[string]dataCached{} + d.mu.Unlock() + log.Printf("[data] index filled: %d packets, %d rows over %d days in %v", n, ix.Len(), d.days, time.Since(clock).Round(time.Millisecond)) + return nil +} + +// refresh re-derives the recent stretch and drops what has aged out. +func (d *dataService) refresh(ctx context.Context) error { + now := d.now() + ix := d.index() + if ix == nil { + return d.fill(ctx) + } + loc := d.locator() + if now.Sub(d.locAt) >= dataLocatorEvery || loc == nil { + l, err := d.loadLocator(ctx) + if err != nil { + return err + } + d.mu.Lock() + d.loc, d.locAt, loc = l, now, l + d.mu.Unlock() + } + since := now.Add(-d.refreshSpan).Truncate(time.Second) + pkts, err := d.readPackets(ctx, "t.first_seen >= ?", since.UTC().Format(dataSQLTimeFormat)) + if err != nil { + return err + } + recs := make([]origin.Record, len(pkts)) + for i := range pkts { + recs[i] = loc.Derive(pkts[i]) + } + // SQL compares first_seen as text from a whole second, and the index + // cuts at the same second, so nothing falls between the two. + ix.Replace(since.Unix(), recs) + ix.Prune(now.Add(-time.Duration(d.days) * 24 * time.Hour).Unix()) + return nil +} + +type dataAdvert struct { + PubKey string `json:"pubKey"` + Lat *float64 `json:"lat"` + Lon *float64 `json:"lon"` + Flags struct { + HasLocation bool `json:"hasLocation"` + } `json:"flags"` + Channel string `json:"channel"` + Hash string `json:"channelHashHex"` +} + +// readPackets reads transmissions matching where, with every observation. +func (d *dataService) readPackets(ctx context.Context, where string, args ...any) ([]origin.Packet, error) { + scope := "NULL" + if d.db.hasScopeName { + scope = "t.scope_name" + } + rows, err := d.db.conn.QueryContext(ctx, `SELECT t.id, t.hash, t.first_seen, COALESCE(t.payload_type, -1), COALESCE(t.route_type, -1), `+scope+`, COALESCE(t.decoded_json, '') + FROM transmissions t WHERE `+where+` ORDER BY t.id`, args...) + if err != nil { + return nil, err + } + byID := map[int64]int{} + var out []origin.Packet + var lo, hi int64 = math.MaxInt64, 0 + for rows.Next() { + var id int64 + var p origin.Packet + var first, decoded string + var sc sql.NullString + if err := rows.Scan(&id, &p.Hash, &first, &p.Type, &p.Route, &sc, &decoded); err != nil { + rows.Close() + return nil, err + } + if t, err := time.Parse(time.RFC3339, first); err == nil { + p.At = t.Unix() + } + p.Scope, p.Scoped = sc.String, sc.Valid + if decoded != "" && (p.Type == 4 || p.Type == 5 || p.Type == 6) { + var a dataAdvert + if json.Unmarshal([]byte(decoded), &a) == nil { + if p.Type == 4 && a.PubKey != "" { + p.Advert = &origin.Advert{PublicKey: a.PubKey} + if a.Flags.HasLocation { + p.Advert.Lat, p.Advert.Lon = a.Lat, a.Lon + } + } + if p.Type != 4 { + switch { + case a.Channel != "": + p.Channel = a.Channel + case a.Hash != "": + p.Channel = "hash:" + strings.ToUpper(a.Hash) + } + } + } + } + byID[id] = len(out) + out = append(out, p) + if id < lo { + lo = id + } + if id > hi { + hi = id + } + } + rows.Close() + if err := rows.Err(); err != nil || len(out) == 0 { + return out, err + } + observer, join := "o.observer_id", "" + if d.db.isV3 { + observer, join = "obs.id", " JOIN observers obs ON obs.rowid = o.observer_idx" + } + resolved := "''" + if d.db.hasResolvedPath { + resolved = "COALESCE(o.resolved_path, '')" + } + orows, err := d.db.conn.QueryContext(ctx, `SELECT o.transmission_id, `+observer+`, COALESCE(o.direction, ''), COALESCE(o.path_json, ''), `+resolved+` + FROM observations o`+join+` WHERE o.transmission_id BETWEEN ? AND ?`, lo, hi) + if err != nil { + return nil, err + } + defer orows.Close() + for orows.Next() { + var tid int64 + var o origin.Observation + var dir, path, res string + if err := orows.Scan(&tid, &o.ObserverID, &dir, &path, &res); err != nil { + return nil, err + } + i, ok := byID[tid] + if !ok { + continue + } + o.Relayed = strings.EqualFold(dir, "tx") + if path != "" && path != "[]" { + _ = json.Unmarshal([]byte(path), &o.Path) + } + if res != "" { + var rp []*string + if json.Unmarshal([]byte(res), &rp) == nil { + o.Resolved = make([]string, len(rp)) + for k, v := range rp { + if v != nil { + o.Resolved[k] = *v + } + } + } + } + out[i].Observations = append(out[i].Observations, o) + } + return out, orows.Err() +} + +// windows are the periods the index reaches. +func (d *dataService) windows() []dataindex.Window { + var out []dataindex.Window + for _, w := range dataindex.Windows { + if w.Span <= time.Duration(d.days)*24*time.Hour { + out = append(out, w) + } + } + return out +} + +func (d *dataService) window(key string) (dataindex.Window, bool) { + for _, w := range d.windows() { + if w.Key == key { + return w, true + } + } + return dataindex.Window{}, false +} + +func (d *dataService) relay(key string) (string, string) { + if loc := d.locator(); loc != nil { + return loc.Relay(key) + } + return strings.ToUpper(key), "" +} + +// cached answers from the cache, building at most once at a time per key. +func (d *dataService) cached(key string, build func() ([]byte, error)) ([]byte, error) { + d.mu.RLock() + c, ok := d.cache[key] + d.mu.RUnlock() + if ok && d.now().Sub(c.at) < dataCacheFor { + return c.body, nil + } + v, err, _ := d.sf.Do(key, func() (any, error) { + b, err := build() + if err != nil { + return nil, err + } + d.mu.Lock() + d.cache[key] = dataCached{at: d.now(), body: b} + d.mu.Unlock() + return b, nil + }) + if err != nil { + return nil, err + } + return v.([]byte), nil +} + +func (d *dataService) cubeJSON(window string) ([]byte, error) { + w, ok := d.window(window) + if !ok { + return nil, errBadWindow + } + return d.cached("cube:"+w.Key, func() ([]byte, error) { + return json.Marshal(d.index().Cube(w, d.now())) + }) +} + +func (d *dataService) summaryJSON(window string) ([]byte, error) { + w, ok := d.window(window) + if !ok { + return nil, errBadWindow + } + return d.cached("summary:"+w.Key, func() ([]byte, error) { + return json.Marshal(d.index().Summary(w, d.now(), d.relay)) + }) +} + +func (d *dataService) packets(window string, from, to int64, fs []dataindex.Filter) dataindex.PacketResult { + w, _ := d.window(window) + return d.index().Packets(w, d.now(), from, to, fs, d.relay) +} + +var errBadWindow = errors.New("no such window") + +func validDataFilters(fs []dataindex.Filter) error { + for _, f := range fs { + ok := false + for _, dim := range dataindex.Dimensions { + if f.D == dim { + ok = true + } + } + if !ok { + return fmt.Errorf("unknown dimension %q", f.D) + } + } + return nil +} + +type dataAreaInfo struct { + Code string `json:"code"` + Label string `json:"label"` +} + +type dataConfigResponse struct { + Enabled bool `json:"enabled"` + Places bool `json:"places"` + Layer string `json:"layer,omitempty"` + Layers []string `json:"layers,omitempty"` + Home string `json:"home,omitempty"` + Areas []dataAreaInfo `json:"areas,omitempty"` + Windows []dataindex.Window `json:"windows,omitempty"` + Groups []dataindex.Group `json:"groups,omitempty"` + TypeNames map[int]string `json:"typeNames,omitempty"` + Dimensions []string `json:"dimensions,omitempty"` + Days int `json:"days,omitempty"` + Rows int `json:"rows"` + CoveredFrom *time.Time `json:"coveredFrom,omitempty"` + Filling bool `json:"filling"` +} + +func writeDataJSON(w http.ResponseWriter, body []byte) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "public, max-age=60") + _, _ = w.Write(body) +} + +// GET /api/data/config +func (s *Server) handleDataConfig(w http.ResponseWriter, r *http.Request) { + d := s.data + if d == nil { + writeJSON(w, dataConfigResponse{Enabled: false}) + return + } + resp := dataConfigResponse{ + Enabled: true, Places: d.places(), Layer: d.layer, Home: d.home, + Windows: d.windows(), Groups: dataindex.Groups, TypeNames: dataindex.TypeNames, + Dimensions: d.dimensions(), Days: d.days, + } + if d.places() { + resp.Layers = d.areas.Layers() + for _, a := range d.areas.Areas(d.layer) { + resp.Areas = append(resp.Areas, dataAreaInfo{Code: a.Code, Label: a.Label}) + } + } + if ix := d.index(); ix != nil { + resp.Rows = ix.Len() + if c := ix.Covered(); c != 0 { + t := time.Unix(c, 0).UTC() + resp.CoveredFrom = &t + } + } + d.mu.RLock() + resp.Filling = d.filling + d.mu.RUnlock() + writeJSON(w, resp) +} + +func (s *Server) dataOr404(w http.ResponseWriter) *dataService { + if s.data == nil { + http.Error(w, "the Data tab is not enabled", http.StatusNotFound) + return nil + } + if s.data.index() == nil { + // On but not built yet: the fill waits for the packet store's + // startup load. Say so, so the page can tell the reader to wait. + http.Error(w, "the Data tab is filling its index; try again shortly", http.StatusServiceUnavailable) + return nil + } + return s.data +} + +func (s *Server) serveDataBuilt(w http.ResponseWriter, body []byte, err error) { + if errors.Is(err, errBadWindow) { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + writeDataJSON(w, body) +} + +// GET /api/data/summary?window= +func (s *Server) handleDataSummary(w http.ResponseWriter, r *http.Request) { + if d := s.dataOr404(w); d != nil { + b, err := d.summaryJSON(r.URL.Query().Get("window")) + s.serveDataBuilt(w, b, err) + } +} + +// GET /api/data/cube?window= +func (s *Server) handleDataCube(w http.ResponseWriter, r *http.Request) { + if d := s.dataOr404(w); d != nil { + b, err := d.cubeJSON(r.URL.Query().Get("window")) + s.serveDataBuilt(w, b, err) + } +} + +// GET /api/data/packets?window=&from=&to=&f= +func (s *Server) handleDataPackets(w http.ResponseWriter, r *http.Request) { + d := s.dataOr404(w) + if d == nil { + return + } + q := r.URL.Query() + if _, ok := d.window(q.Get("window")); !ok { + http.Error(w, errBadWindow.Error(), http.StatusBadRequest) + return + } + var fs []dataindex.Filter + if f := q.Get("f"); f != "" { + if err := json.Unmarshal([]byte(f), &fs); err != nil { + http.Error(w, "f must be a JSON list of filters", http.StatusBadRequest) + return + } + if err := validDataFilters(fs); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + } + from, _ := strconv.ParseInt(q.Get("from"), 10, 64) + to, _ := strconv.ParseInt(q.Get("to"), 10, 64) + select { + case d.slots <- struct{}{}: + defer func() { <-d.slots }() + case <-r.Context().Done(): + return + } + b, err := json.Marshal(d.packets(q.Get("window"), from, to, fs)) + s.serveDataBuilt(w, b, err) +} + +// placedIndex is the index when packets are placed in areas; nil otherwise. +func (d *dataService) placedIndex() *dataindex.Index { + if d == nil || !d.places() { + return nil + } + return d.index() +} + +// startedIn tests hashes for packets that started in area; nil when the +// index cannot place in that area. +func (d *dataService) startedIn(area string) func(hash string) bool { + if ix := d.placedIndex(); ix != nil && area != "" { + return ix.StartedIn(area) + } + return nil +} + +// withOrigins returns res with where each listed packet started, or res +// itself when packets are not placed. res may be shared with a cache, so +// it is copied, never changed. +func (d *dataService) withOrigins(res *PacketResult) *PacketResult { + ix := d.placedIndex() + if ix == nil || res == nil { + return res + } + hashes := make([]string, 0, len(res.Packets)) + for _, p := range res.Packets { + if h, ok := p["hash"].(string); ok && h != "" { + hashes = append(hashes, h) + } + } + out := *res + out.Origins = ix.OriginsOf(hashes) + return &out +} + +// originOf is where one packet started, or nil. +func (d *dataService) originOf(hash string) *dataindex.Origin { + ix := d.placedIndex() + if ix == nil || hash == "" { + return nil + } + if o, ok := ix.OriginsOf([]string{hash})[hash]; ok { + return &o + } + return nil +} diff --git a/cmd/server/data_dashboards.go b/cmd/server/data_dashboards.go new file mode 100644 index 000000000..7db3fdfe7 --- /dev/null +++ b/cmd/server/data_dashboards.go @@ -0,0 +1,404 @@ +package main + +// Data tab dashboards: a dashboard is a JSON document of panels, each a +// query over the Data tab's cube and a way to draw it. CoreScope ships a +// couple of generic ones; an operator can offer more from a file +// (data.dashboardsFile); visitors build and export their own in the browser. +// The server only validates and serves them: it stores nothing. + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "regexp" + + "github.com/meshcore-analyzer/dataindex" +) + +// DashboardVariable is a value chosen on the page and written into panels as +// $name: an area, a scope, a channel or free text. +type DashboardVariable struct { + Name string `json:"name"` + Kind string `json:"kind"` + Label string `json:"label,omitempty"` + Default string `json:"default,omitempty"` +} + +// DashboardQuery is what a panel counts. Fields a panel type does not use +// are left empty. +type DashboardQuery struct { + Window string `json:"window,omitempty"` + Filters []dataindex.Filter `json:"filters,omitempty"` + X string `json:"x,omitempty"` + Split string `json:"split,omitempty"` + Facet string `json:"facet,omitempty"` + Mode string `json:"mode,omitempty"` + Rollup string `json:"rollup,omitempty"` + Pick []string `json:"pick,omitempty"` + Rows string `json:"rows,omitempty"` + Cols string `json:"cols,omitempty"` + Dim string `json:"dim,omitempty"` + Top int `json:"top,omitempty"` + // From and To are the two repeaters a watch panel follows: public keys, + // or $variables of the repeater kind. + From string `json:"from,omitempty"` + To string `json:"to,omitempty"` + // Basis is "adverts" to count only adverts on a watch (steadier), else all. + Basis string `json:"basis,omitempty"` + // FlagDays is how long a route change stays a watch's flag (default 7). + FlagDays int `json:"flagDays,omitempty"` +} + +// DashboardWatch is one pair a watch list follows. +type DashboardWatch struct { + Name string `json:"name"` + From string `json:"from"` + To string `json:"to"` + Both bool `json:"both,omitempty"` // show the way back too +} + +// DashboardPanelOptions holds the settings only some panel types have. +type DashboardPanelOptions struct { + Text string `json:"text,omitempty"` + Watches []DashboardWatch `json:"watches,omitempty"` // a watchlist's pairs +} + +// DashboardLayout is a panel's place on the 12-column grid. +type DashboardLayout struct { + X int `json:"x"` + Y int `json:"y"` + W int `json:"w"` + H int `json:"h"` +} + +// DashboardPanel is one panel. +type DashboardPanel struct { + ID string `json:"id"` + Title string `json:"title"` + Type string `json:"type"` + Query DashboardQuery `json:"query"` + Options *DashboardPanelOptions `json:"options,omitempty"` + Layout DashboardLayout `json:"layout"` +} + +// Dashboard is one dashboard document, schema 1. +type Dashboard struct { + Schema int `json:"schema"` + ID string `json:"id"` + Title string `json:"title"` + Description string `json:"description,omitempty"` + Window string `json:"window,omitempty"` + Variables []DashboardVariable `json:"variables,omitempty"` + Panels []DashboardPanel `json:"panels"` + // Source is set by the server: "built-in" or "operator". Never read + // from a file. + Source string `json:"source,omitempty"` +} + +// DataDashboards is what GET /api/data/dashboards serves. +type DataDashboards struct { + Default string `json:"default"` + Home string `json:"home,omitempty"` + Dashboards []Dashboard `json:"dashboards"` +} + +// Limits, so a mistake in a file cannot put thousands of panels on a page. +const ( + maxDashboards = 50 + maxDashboardPanels = 24 + maxDashboardsFileBytes = 1 << 20 + maxDashboardTextBytes = 4000 +) + +var ( + dashboardIDRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`) + dashboardVarRe = regexp.MustCompile(`^[a-z][a-z0-9_]{0,31}$`) + panelTypes = map[string]bool{"bar": true, "line": true, "area": true, "matrix": true, "stat": true, "table": true, "top": true, "text": true, "watch": true, "watchlist": true} + variableKinds = map[string]bool{"area": true, "scope": true, "channel": true, "text": true, "repeater": true} + watchEndRe = regexp.MustCompile(`^([0-9a-f]{64}|\$[a-z][a-z0-9_]{0,31})$`) + dashWindows = map[string]bool{"": true, "24h": true, "7d": true, "30d": true} + rollups = map[string]bool{"": true, "10m": true, "30m": true, "1h": true, "6h": true, "1d": true, "1w": true} +) + +func isDimension(d string) bool { + for _, k := range dataindex.Dimensions { + if k == d { + return true + } + } + return false +} + +// optionalDim accepts "" or a known dimension; extra lists other words +// allowed in that field (the X axis also takes "time"). +func optionalDim(field, v string, extra ...string) error { + if v == "" || isDimension(v) { + return nil + } + for _, e := range extra { + if v == e { + return nil + } + } + return fmt.Errorf("%s %q is not a dimension", field, v) +} + +func validatePanel(p DashboardPanel) error { + if !dashboardIDRe.MatchString(p.ID) { + return fmt.Errorf("panel id %q: use lower-case letters, digits and dashes", p.ID) + } + if p.Title == "" || len(p.Title) > 120 { + return fmt.Errorf("panel %q needs a title of at most 120 characters", p.ID) + } + if !panelTypes[p.Type] { + return fmt.Errorf("panel %q: unknown type %q", p.ID, p.Type) + } + q := p.Query + if !dashWindows[q.Window] || !rollups[q.Rollup] || (q.Mode != "" && q.Mode != "count" && q.Mode != "share") { + return fmt.Errorf("panel %q: window, rollup or mode is not one the tab knows", p.ID) + } + for _, f := range q.Filters { + if !isDimension(f.D) { + return fmt.Errorf("panel %q: filter dimension %q is unknown", p.ID, f.D) + } + } + for _, chk := range []error{optionalDim("x", q.X, "time"), optionalDim("split", q.Split), optionalDim("facet", q.Facet), optionalDim("rows", q.Rows), optionalDim("cols", q.Cols), optionalDim("dim", q.Dim)} { + if chk != nil { + return fmt.Errorf("panel %q: %w", p.ID, chk) + } + } + if q.Top < 0 || q.Top > 50 { + return fmt.Errorf("panel %q: top must be 1 to 50", p.ID) + } + if p.Options != nil && len(p.Options.Text) > maxDashboardTextBytes { + return fmt.Errorf("panel %q: text is longer than %d bytes", p.ID, maxDashboardTextBytes) + } + if q.Basis != "" && q.Basis != "all" && q.Basis != "adverts" { + return fmt.Errorf("panel %q: basis must be all or adverts", p.ID) + } + if q.FlagDays < 0 || q.FlagDays > 21 { + return fmt.Errorf("panel %q: flagDays must be 1 to 21", p.ID) + } + switch p.Type { + case "watch": + if !watchEndRe.MatchString(q.From) || !watchEndRe.MatchString(q.To) || q.From == q.To { + return fmt.Errorf("panel %q: a watch needs two different repeaters, by public key or $variable", p.ID) + } + case "watchlist": + if p.Options == nil || len(p.Options.Watches) == 0 || len(p.Options.Watches) > pathMaxPairs { + return fmt.Errorf("panel %q: a watch list needs 1 to %d watches", p.ID, pathMaxPairs) + } + for _, wt := range p.Options.Watches { + if wt.Name == "" || len(wt.Name) > 80 || !pubkeyRe.MatchString(wt.From) || !pubkeyRe.MatchString(wt.To) || wt.From == wt.To { + return fmt.Errorf("panel %q: watch %q needs a name of at most 80 characters and two different repeater public keys", p.ID, wt.Name) + } + } + } + l := p.Layout + if l.W < 1 || l.W > 12 || l.H < 1 || l.H > 12 || l.X < 0 || l.X+l.W > 12 || l.Y < 0 { + return fmt.Errorf("panel %q: layout must fit the 12-column grid", p.ID) + } + return nil +} + +// placeUse names the first thing in d that needs areas: an area variable or a +// place dimension in any panel. "" when d works without areas. +func placeUse(d Dashboard) string { + for _, v := range d.Variables { + if v.Kind == "area" { + return fmt.Sprintf("variable %q is an area", v.Name) + } + } + for _, p := range d.Panels { + q := p.Query + for _, dim := range []string{q.X, q.Split, q.Facet, q.Rows, q.Cols, q.Dim} { + if dataindex.PlaceDimensions[dim] { + return fmt.Sprintf("panel %q uses %q", p.ID, dim) + } + } + for _, f := range q.Filters { + if dataindex.PlaceDimensions[f.D] { + return fmt.Sprintf("panel %q filters on %q", p.ID, f.D) + } + } + } + return "" +} + +func validateDashboard(d Dashboard) error { + if d.Schema != 1 { + return fmt.Errorf("dashboard %q uses schema %d; this CoreScope reads schema 1", d.ID, d.Schema) + } + if !dashboardIDRe.MatchString(d.ID) { + return fmt.Errorf("dashboard id %q: use lower-case letters, digits and dashes", d.ID) + } + if d.Title == "" || len(d.Title) > 120 { + return fmt.Errorf("dashboard %q needs a title of at most 120 characters", d.ID) + } + if !dashWindows[d.Window] { + return fmt.Errorf("dashboard %q: window %q is not 24h, 7d or 30d", d.ID, d.Window) + } + if len(d.Panels) > maxDashboardPanels { + return fmt.Errorf("dashboard %q has %d panels; at most %d", d.ID, len(d.Panels), maxDashboardPanels) + } + vars := map[string]bool{} + for _, v := range d.Variables { + if !dashboardVarRe.MatchString(v.Name) || !variableKinds[v.Kind] || vars[v.Name] { + return fmt.Errorf("dashboard %q: variable %q needs a unique lower-case name and a kind of area, scope, channel, repeater or text", d.ID, v.Name) + } + vars[v.Name] = true + } + seen := map[string]bool{} + for _, p := range d.Panels { + if err := validatePanel(p); err != nil { + return fmt.Errorf("dashboard %q: %w", d.ID, err) + } + if seen[p.ID] { + return fmt.Errorf("dashboard %q: panel id %q is used twice", d.ID, p.ID) + } + seen[p.ID] = true + } + return nil +} + +// LoadDataDashboards returns the built-in dashboards followed by the +// operator's, validated. A bad file is an error, so startup stops with the +// reason rather than serving half a set. +func LoadDataDashboards(cfg *Config, configDir string) (*DataDashboards, error) { + out := &DataDashboards{} + ids := map[string]bool{} + places := cfg.hasAreas() + for _, d := range builtInDashboards(places) { + d.Source = "built-in" + out.Dashboards = append(out.Dashboards, d) + ids[d.ID] = true + } + dc := cfg.Data + if dc != nil { + out.Home = dc.HomeArea + } + if dc != nil && dc.DashboardsFile != "" { + path := dc.DashboardsFile + if !filepath.IsAbs(path) { + path = filepath.Join(configDir, path) + } + f, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("data.dashboardsFile: %w", err) + } + raw, err := io.ReadAll(io.LimitReader(f, maxDashboardsFileBytes+1)) + f.Close() + if err != nil { + return nil, fmt.Errorf("data.dashboardsFile: %w", err) + } + if len(raw) > maxDashboardsFileBytes { + return nil, fmt.Errorf("data.dashboardsFile is larger than %d bytes", maxDashboardsFileBytes) + } + var list []Dashboard + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.DisallowUnknownFields() + if err := dec.Decode(&list); err != nil { + return nil, fmt.Errorf("data.dashboardsFile %s: %w", path, err) + } + if len(list) > maxDashboards { + return nil, fmt.Errorf("data.dashboardsFile has %d dashboards; at most %d", len(list), maxDashboards) + } + for _, d := range list { + if err := validateDashboard(d); err != nil { + return nil, fmt.Errorf("data.dashboardsFile: %w", err) + } + if use := placeUse(d); use != "" && !places { + return nil, fmt.Errorf("data.dashboardsFile: dashboard %q: %s, which needs areas: set areasFile or areas in config.json, or drop it", d.ID, use) + } + if ids[d.ID] { + return nil, fmt.Errorf("data.dashboardsFile: dashboard id %q is already used", d.ID) + } + ids[d.ID] = true + d.Source = "operator" + out.Dashboards = append(out.Dashboards, d) + } + } + out.Default = out.Dashboards[0].ID + if dc != nil && dc.DefaultDashboard != "" { + if !ids[dc.DefaultDashboard] { + return nil, fmt.Errorf("data.defaultDashboard %q is not a dashboard", dc.DefaultDashboard) + } + out.Default = dc.DefaultDashboard + } + return out, nil +} + +// builtInDashboards are generic: they need an areas file at most. Without +// areas (places false) they keep to kind, type, channel, scope and routing. +// The last, Path, follows any two repeaters picked at the top. +func builtInDashboards(places bool) []Dashboard { + return append(builtInCubeDashboards(places), Dashboard{Schema: 1, ID: "path", Title: "Path between two repeaters", Window: "7d", + Description: "How much of what passes the first repeater gets to the second, the routes it takes and when they change. Pick the two at the top.", + Variables: []DashboardVariable{{Name: "from", Kind: "repeater", Label: "From"}, {Name: "to", Kind: "repeater", Label: "To"}}, + Panels: []DashboardPanel{{ID: "watch", Title: "$from to $to", Type: "watch", Query: DashboardQuery{From: "$from", To: "$to"}, Layout: DashboardLayout{W: 12, H: 8}}}}) +} + +func builtInCubeDashboards(places bool) []Dashboard { + lay := func(x, y, w, h int) DashboardLayout { return DashboardLayout{X: x, Y: y, W: w, H: h} } + notChannel := dataindex.Filter{D: "channel", N: 1, V: []string{""}} + adverts := dataindex.Filter{D: "kind", V: []string{"adverts"}} + if !places { + return []Dashboard{ + {Schema: 1, ID: "overview", Title: "Overview", Window: "24h", + Description: "Every packet heard, by kind, scope and channel.", + Panels: []DashboardPanel{ + {ID: "packets", Title: "Packets heard", Type: "stat", Layout: lay(0, 0, 4, 2)}, + {ID: "adverts", Title: "Flood adverts", Type: "stat", Query: DashboardQuery{Filters: []dataindex.Filter{adverts}}, Layout: lay(4, 0, 4, 2)}, + {ID: "messages", Title: "Messages", Type: "stat", Query: DashboardQuery{Filters: []dataindex.Filter{{D: "kind", V: []string{"messages"}}}}, Layout: lay(8, 0, 4, 2)}, + {ID: "by-kind", Title: "Packets over time by kind", Type: "area", Query: DashboardQuery{X: "time", Split: "kind"}, Layout: lay(0, 2, 8, 4)}, + {ID: "top-scopes", Title: "Busiest scopes", Type: "top", Query: DashboardQuery{Dim: "scope", Top: 8}, Layout: lay(8, 2, 4, 4)}, + {ID: "top-channels", Title: "Busiest channels", Type: "top", Query: DashboardQuery{Dim: "channel", Top: 8, Filters: []dataindex.Filter{notChannel}}, Layout: lay(0, 6, 5, 5)}, + {ID: "types", Title: "Packet types by routing", Type: "table", Query: DashboardQuery{X: "type", Split: "routing"}, Layout: lay(5, 6, 7, 5)}, + }}, + {Schema: 1, ID: "scopes", Title: "Scopes and channels", Window: "7d", + Description: "Which region scopes and channels carry traffic, and what kind.", + Panels: []DashboardPanel{ + {ID: "scope-time", Title: "Packets by scope", Type: "bar", Query: DashboardQuery{X: "time", Split: "scope", Rollup: "6h"}, Layout: lay(0, 0, 8, 4)}, + {ID: "scope-kinds", Title: "Scope kinds", Type: "top", Query: DashboardQuery{Dim: "sclass", Top: 4}, Layout: lay(8, 0, 4, 4)}, + {ID: "scope-kind", Title: "Scope by packet kind", Type: "matrix", Query: DashboardQuery{Rows: "scope", Cols: "kind"}, Layout: lay(0, 4, 7, 5)}, + {ID: "channel-time", Title: "Channel traffic", Type: "line", Query: DashboardQuery{X: "time", Split: "channel", Rollup: "6h", Filters: []dataindex.Filter{notChannel}}, Layout: lay(7, 4, 5, 5)}, + }}, + } + } + crossed := dataindex.Filter{D: "border", V: []string{"crossed"}} + return []Dashboard{ + {Schema: 1, ID: "overview", Title: "Overview", Window: "24h", + Description: "Every packet heard, by kind, by the area it started in and the areas that heard it.", + Panels: []DashboardPanel{ + {ID: "packets", Title: "Packets heard", Type: "stat", Layout: lay(0, 0, 3, 2)}, + {ID: "crossed", Title: "Heard outside their start", Type: "stat", Query: DashboardQuery{Filters: []dataindex.Filter{crossed}}, Layout: lay(3, 0, 3, 2)}, + {ID: "adverts", Title: "Flood adverts", Type: "stat", Query: DashboardQuery{Filters: []dataindex.Filter{adverts}}, Layout: lay(6, 0, 3, 2)}, + {ID: "unknown", Title: "Start not known", Type: "stat", Query: DashboardQuery{Filters: []dataindex.Filter{{D: "border", V: []string{"unknown"}}}}, Layout: lay(9, 0, 3, 2)}, + {ID: "by-kind", Title: "Packets over time by kind", Type: "area", Query: DashboardQuery{X: "time", Split: "kind"}, Layout: lay(0, 2, 8, 4)}, + {ID: "top-scopes", Title: "Busiest scopes", Type: "top", Query: DashboardQuery{Dim: "scope", Top: 8}, Layout: lay(8, 2, 4, 4)}, + {ID: "matrix", Title: "Who hears whom", Type: "matrix", Query: DashboardQuery{Rows: "origin", Cols: "heard"}, Layout: lay(0, 6, 8, 5)}, + {ID: "top-channels", Title: "Busiest channels", Type: "top", Query: DashboardQuery{Dim: "channel", Top: 8, Filters: []dataindex.Filter{notChannel}}, Layout: lay(8, 6, 4, 5)}, + }}, + {Schema: 1, ID: "scopes", Title: "Scopes and channels", Window: "7d", + Description: "Which region scopes and channels carry traffic, and where they are heard.", + Panels: []DashboardPanel{ + {ID: "scope-time", Title: "Packets by scope", Type: "bar", Query: DashboardQuery{X: "time", Split: "scope", Rollup: "6h"}, Layout: lay(0, 0, 8, 4)}, + {ID: "scope-kinds", Title: "Scope kinds", Type: "top", Query: DashboardQuery{Dim: "sclass", Top: 4}, Layout: lay(8, 0, 4, 4)}, + {ID: "scope-heard", Title: "Scope by receiving area", Type: "matrix", Query: DashboardQuery{Rows: "scope", Cols: "heard"}, Layout: lay(0, 4, 7, 5)}, + {ID: "channel-time", Title: "Channel traffic", Type: "line", Query: DashboardQuery{X: "time", Split: "channel", Rollup: "6h", Filters: []dataindex.Filter{notChannel}}, Layout: lay(7, 4, 5, 5)}, + }}, + } +} + +// GET /api/data/dashboards +func (s *Server) handleDataDashboards(w http.ResponseWriter, r *http.Request) { + if s.data == nil || s.data.dashboards == nil { + http.Error(w, "the Data tab is not enabled", http.StatusNotFound) + return + } + writeJSON(w, s.data.dashboards) +} diff --git a/cmd/server/data_dashboards_test.go b/cmd/server/data_dashboards_test.go new file mode 100644 index 000000000..bad7d8cd5 --- /dev/null +++ b/cmd/server/data_dashboards_test.go @@ -0,0 +1,152 @@ +package main + +import ( + "context" + "net/http" + "os" + "path/filepath" + "strings" + "testing" +) + +const goodDashboards = `[ + {"schema":1,"id":"cross-border","title":"Cross-border traffic","window":"7d", + "variables":[{"name":"home","kind":"area","default":"SCO"}], + "panels":[ + {"id":"leaving","title":"Leaving $home","type":"stat", + "query":{"filters":[{"d":"border","v":["crossed"]},{"d":"origin","v":["$home"]}]}, + "layout":{"x":0,"y":0,"w":3,"h":2}}, + {"id":"matrix","title":"Who hears whom","type":"matrix","query":{"rows":"origin","cols":"heard"}, + "layout":{"x":0,"y":2,"w":12,"h":5}}, + {"id":"note","title":"About","type":"text","options":{"text":"Counts by **start**."},"layout":{"x":3,"y":0,"w":9,"h":2}} + ]} +]` + +func writeDashboards(t *testing.T, body string) string { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "dashboards.json"), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + return dir +} + +func TestLoadDataDashboardsReadsTheFile(t *testing.T) { + // goodDashboards has an area variable, so this deployment has areas. + dir := writeDashboards(t, goodDashboards) + if err := os.WriteFile(filepath.Join(dir, "areas.geojson"), []byte(dataAreasGeoJSON), 0o644); err != nil { + t.Fatal(err) + } + cfg := &Config{AreasFile: "areas.geojson", Data: &DataConfig{Enabled: true, DashboardsFile: "dashboards.json", DefaultDashboard: "cross-border"}} + if _, err := LoadAreaMap(cfg, dir); err != nil { + t.Fatal(err) + } + ds, err := LoadDataDashboards(cfg, dir) + if err != nil { + t.Fatal(err) + } + if len(ds.Dashboards) < 2 || ds.Dashboards[0].Source != "built-in" { + t.Fatalf("dashboards = %+v, want the built-in ones first", ds.Dashboards) + } + last := ds.Dashboards[len(ds.Dashboards)-1] + if last.ID != "cross-border" || last.Source != "operator" || len(last.Panels) != 3 { + t.Errorf("operator dashboard = %+v", last) + } + if ds.Default != "cross-border" { + t.Errorf("default = %q, want cross-border", ds.Default) + } +} + +func TestLoadDataDashboardsWithoutAFileGivesTheBuiltIns(t *testing.T) { + ds, err := LoadDataDashboards(&Config{Data: &DataConfig{Enabled: true}}, t.TempDir()) + if err != nil { + t.Fatal(err) + } + if len(ds.Dashboards) == 0 || ds.Default != ds.Dashboards[0].ID { + t.Errorf("no file: %d dashboards, default %q; want the built-ins with the first as default", len(ds.Dashboards), ds.Default) + } + for _, d := range ds.Dashboards { + if err := validateDashboard(d); err != nil { + t.Errorf("built-in %q does not validate: %v", d.ID, err) + } + } +} + +func TestLoadDataDashboardsRefusesBadFiles(t *testing.T) { + panel := `{"id":"p","title":"P","type":"bar","query":{},"layout":{"x":0,"y":0,"w":6,"h":4}}` + dash := func(extra string) string { + return `[{"schema":1,"id":"d","title":"D",` + extra + `}]` + } + cases := map[string]string{ + "invalid JSON": `[{`, + "schema 2": `[{"schema":2,"id":"d","title":"D","panels":[]}]`, + "no title": `[{"schema":1,"id":"d","panels":[]}]`, + "bad id": `[{"schema":1,"id":"Not OK","title":"D","panels":[]}]`, + "unknown field": dash(`"panels":[],"colour":"red"`), + "unknown panel type": dash(`"panels":[{"id":"p","title":"P","type":"pie","query":{},"layout":{"x":0,"y":0,"w":6,"h":4}}]`), + "unknown dimension": dash(`"panels":[{"id":"p","title":"P","type":"bar","query":{"filters":[{"d":"colour","v":["x"]}]},"layout":{"x":0,"y":0,"w":6,"h":4}}]`), + "unknown split": dash(`"panels":[{"id":"p","title":"P","type":"bar","query":{"split":"colour"},"layout":{"x":0,"y":0,"w":6,"h":4}}]`), + "too wide": dash(`"panels":[{"id":"p","title":"P","type":"bar","query":{},"layout":{"x":0,"y":0,"w":13,"h":4}}]`), + "duplicate panel": dash(`"panels":[` + panel + `,` + panel + `]`), + "bad window": dash(`"window":"1y","panels":[]`), + "bad variable": dash(`"variables":[{"name":"Home Area","kind":"area"}],"panels":[]`), + "clashes with built-in": `[{"schema":1,"id":"overview","title":"Mine","panels":[]}]`, + "duplicate dashboard": `[{"schema":1,"id":"a","title":"A","panels":[]},{"schema":1,"id":"a","title":"B","panels":[]}]`, + } + // 25 distinct panels. + var ps []string + for i := 0; i < 25; i++ { + ps = append(ps, strings.Replace(panel, `"id":"p"`, `"id":"p`+strings.Repeat("x", i+1)+`"`, 1)) + } + cases["too many panels"] = dash(`"panels":[` + strings.Join(ps, ",") + `]`) + for name, body := range cases { + dir := writeDashboards(t, body) + cfg := &Config{Data: &DataConfig{Enabled: true, DashboardsFile: "dashboards.json"}} + if _, err := LoadDataDashboards(cfg, dir); err == nil { + t.Errorf("%s: loaded, want refused", name) + } + } + if _, err := LoadDataDashboards(&Config{Data: &DataConfig{Enabled: true, DashboardsFile: "missing.json"}}, t.TempDir()); err == nil { + t.Error("a missing file should be refused") + } + dir := writeDashboards(t, goodDashboards) + if _, err := LoadDataDashboards(&Config{Data: &DataConfig{Enabled: true, DashboardsFile: "dashboards.json", DefaultDashboard: "nope"}}, dir); err == nil { + t.Error("a default naming no dashboard should be refused") + } +} + +func TestDataDashboardsEndpoint(t *testing.T) { + f := newDataFixture(t, true) + dir := writeDashboards(t, goodDashboards) + f.cfg.Data.DashboardsFile = "dashboards.json" + ds, err := LoadDataDashboards(f.cfg, dir) + if err != nil { + t.Fatal(err) + } + f.svc.dashboards = ds + if err := f.svc.fill(context.Background()); err != nil { + t.Fatal(err) + } + r := dataRouter(f) + r.HandleFunc("/api/data/dashboards", (&Server{db: f.db, cfg: f.cfg, data: f.svc}).handleDataDashboards).Methods("GET") + var got struct { + Default string `json:"default"` + Home string `json:"home"` + Dashboards []struct { + ID, Source string + Panels []struct{ Type string } + } `json:"dashboards"` + } + if code := getJSON(t, r, "/api/data/dashboards", &got); code != http.StatusOK { + t.Fatalf("status %d", code) + } + if got.Home != "SCO" || len(got.Dashboards) < 2 || got.Dashboards[len(got.Dashboards)-1].ID != "cross-border" { + t.Errorf("dashboards response = %+v", got) + } + off := newDataFixture(t, false) + ro := dataRouter(off) + ro.HandleFunc("/api/data/dashboards", (&Server{db: off.db, cfg: off.cfg}).handleDataDashboards).Methods("GET") + if code := getJSON(t, ro, "/api/data/dashboards", nil); code != http.StatusNotFound { + t.Errorf("tab off: status %d, want 404", code) + } +} diff --git a/cmd/server/data_packet_origin_test.go b/cmd/server/data_packet_origin_test.go new file mode 100644 index 000000000..cb494b0e6 --- /dev/null +++ b/cmd/server/data_packet_origin_test.go @@ -0,0 +1,114 @@ +package main + +import ( + "context" + "sort" + "testing" + + "github.com/gorilla/mux" +) + +// packetOriginRouter serves /api/packets from a loaded packet store, with the +// Data tab's index beside it when the fixture has one. +func packetOriginRouter(t *testing.T, f *dataFixture) *mux.Router { + t.Helper() + store := NewPacketStore(f.db, nil) + f.cfg.applyListLimitsDefaults() + store.config = f.cfg + if err := store.Load(); err != nil { + t.Fatal(err) + } + if f.svc != nil { + if err := f.svc.fill(context.Background()); err != nil { + t.Fatal(err) + } + } + srv := &Server{db: f.db, cfg: f.cfg, store: store, data: f.svc} + r := mux.NewRouter() + r.HandleFunc("/api/packets/{id}", srv.handlePacketDetail).Methods("GET") + r.HandleFunc("/api/packets", srv.handlePackets).Methods("GET") + return r +} + +type packetListWithOrigins struct { + Packets []struct { + Hash string `json:"hash"` + } `json:"packets"` + Origins map[string]struct { + Area string `json:"area"` + Basis string `json:"basis"` + } `json:"origins"` +} + +func (p packetListWithOrigins) hashes() []string { + out := []string{} + for _, x := range p.Packets { + out = append(out, x.Hash) + } + sort.Strings(out) + return out +} + +// An area keeps the packets that started there, whatever their type: the +// Scottish channel message p1 is not an advert but started in SCO (its first +// relay stands in Edinburgh), and the Irish advert a2 did not. +func TestPacketsAreaFilterKeepsPacketsByOrigin(t *testing.T) { + f := newDataFixture(t, true) + r := packetOriginRouter(t, f) + for _, path := range []string{"/api/packets?area=SCO", "/api/packets?area=SCO&groupByHash=true"} { + var res packetListWithOrigins + if code := getJSON(t, r, path, &res); code != 200 { + t.Fatalf("%s = %d", path, code) + } + if got := res.hashes(); len(got) != 1 || got[0] != "00000000000000p1" { + t.Errorf("%s = %v, want just the Scottish channel message", path, got) + } + } + var ioi packetListWithOrigins + getJSON(t, r, "/api/packets?area=IOI", &ioi) + if got := ioi.hashes(); len(got) != 1 || got[0] != "00000000000000a2" { + t.Errorf("area=IOI = %v, want the Irish advert", got) + } +} + +// With areas the list says where each packet started and how that was decided. +func TestPacketsListCarriesOrigins(t *testing.T) { + f := newDataFixture(t, true) + r := packetOriginRouter(t, f) + for _, path := range []string{"/api/packets", "/api/packets?groupByHash=true"} { + var res packetListWithOrigins + getJSON(t, r, path, &res) + if res.Origins == nil { + t.Fatalf("%s: no origins", path) + } + if o := res.Origins["00000000000000p1"]; o.Area != "SCO" || o.Basis != "first-relay" { + t.Errorf("%s: p1 origin = %+v, want SCO by first relay", path, o) + } + if o := res.Origins["00000000000000a2"]; o.Area != "IOI" || o.Basis != "advert" { + t.Errorf("%s: a2 origin = %+v, want IOI by its advert", path, o) + } + } + var detail struct { + Origin *struct { + Area string `json:"area"` + Basis string `json:"basis"` + } `json:"origin"` + } + // The detail route takes 16 hex digits, so ask for the advert (p1's hash + // is not hex). + getJSON(t, r, "/api/packets/00000000000000a2", &detail) + if detail.Origin == nil || detail.Origin.Area != "IOI" || detail.Origin.Basis != "advert" { + t.Errorf("packet detail origin = %+v, want IOI by its advert", detail.Origin) + } +} + +// Without the Data tab there is no origin to give, and the list says nothing. +func TestPacketsListWithoutDataHasNoOrigins(t *testing.T) { + f := newDataFixture(t, false) + r := packetOriginRouter(t, f) + var res packetListWithOrigins + getJSON(t, r, "/api/packets", &res) + if res.Origins != nil { + t.Errorf("origins = %v, want none without the Data tab", res.Origins) + } +} diff --git a/cmd/server/data_path.go b/cmd/server/data_path.go new file mode 100644 index 000000000..f4c2668fa --- /dev/null +++ b/cmd/server/data_path.go @@ -0,0 +1,428 @@ +package main + +// Path watch: the Data tab's "watch" and "watchlist" panels follow the path +// between two repeaters. The packet store already indexes, for every +// repeater, the packets whose resolved path names it (byPathHop), so a watch +// is the packets that passed A, and among those that also name B, the ones +// whose path reaches B after A. Only those have their resolved paths read +// (batched, through the store's own loader); the rest is counted in memory. +// internal/pathwatch turns that into days, routes and route changes. +// Read-only; answers are cached for a few minutes per pair. + +import ( + "encoding/json" + "fmt" + "net/http" + "regexp" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/meshcore-analyzer/pathwatch" +) + +const ( + pathCacheFor = 5 * time.Minute + pathCacheMax = 256 + pathMaxPairs = 24 + pathBaseDays = 14 // a share's usual comes from this many days before + advertPayload = 4 +) + +var pubkeyRe = regexp.MustCompile(`^[0-9a-f]{64}$`) + +// DataPathNode is a repeater by key and name. +type DataPathNode struct { + Key string `json:"key"` + Name string `json:"name"` +} + +// DataPathDay is one 24-hour bucket, the last 24 hours last. +type DataPathDay struct { + Day string `json:"day"` // its start, RFC3339 + Passed int `json:"passed"` + Reached int `json:"reached"` + Share float64 `json:"share"` // -1 when too few passed to say +} + +// DataPathRoute is one way the packets went between the two. +type DataPathRoute struct { + Via []DataPathNode `json:"via"` // empty: straight from one to the other + Share float64 `json:"share"` + Usual float64 `json:"usual"` +} + +// DataPathChange is a change of route, said in words. +type DataPathChange struct { + Day string `json:"day"` + Kind string `json:"kind"` // repeater-quiet, rerouted, new-repeater, sharing, route-changed, route-share + Node *DataPathNode `json:"node,omitempty"` + Was float64 `json:"was"` + Now float64 `json:"now"` + From []DataPathNode `json:"from,omitempty"` + To []DataPathNode `json:"to,omitempty"` + ShareWas float64 `json:"shareWas"` + ShareNow float64 `json:"shareNow"` + Text string `json:"text"` +} + +// DataPathResponse is GET /api/data/path. +type DataPathResponse struct { + From DataPathNode `json:"from"` + To DataPathNode `json:"to"` + Window string `json:"window"` + Basis string `json:"basis"` + Days []DataPathDay `json:"days"` + Share float64 `json:"share"` + Usual float64 `json:"usual"` + Low float64 `json:"low"` + High float64 `json:"high"` + Verdict string `json:"verdict"` + Hops pathwatch.Hops `json:"hops"` + Routes []DataPathRoute `json:"routes"` + Changes []DataPathChange `json:"changes"` + Flag *DataPathChange `json:"flag,omitempty"` +} + +// DataPathPair is one pair in a batch. +type DataPathPair struct { + From string `json:"from"` + To string `json:"to"` +} + +// DataPathsRequest is the body of POST /api/data/paths. +type DataPathsRequest struct { + Window string `json:"window"` + Basis string `json:"basis"` + FlagDays int `json:"flagDays,omitempty"` // how long a change stays a flag (default 7, at most 21) + Pairs []DataPathPair `json:"pairs"` +} + +// DataPathsResponse answers it, in the same order. +type DataPathsResponse struct { + Paths []DataPathResponse `json:"paths"` +} + +type pathCached struct { + at time.Time + resp DataPathResponse +} + +type pathCache struct { + mu sync.Mutex + m map[string]pathCached +} + +var pathCaches sync.Map // *pathIndex -> *pathCache + +func (s *Server) pathCacheFor() *pathCache { + c, _ := pathCaches.LoadOrStore(s.paths, &pathCache{m: map[string]pathCached{}}) + return c.(*pathCache) +} + +func (s *Server) pathOr404(w http.ResponseWriter) bool { + if !s.cfg.DataEnabled() || s.paths == nil { + http.Error(w, "path watch is part of the Data tab (data.enabled in config.json)", http.StatusNotFound) + return false + } + if !s.paths.isReady() { + http.Error(w, "path watch is still reading its history; try again in a minute", http.StatusServiceUnavailable) + return false + } + return true +} + +func pathFlagDays(v string) (int, bool) { + if v == "" { + return 7, true + } + n, err := strconv.Atoi(v) + return n, err == nil && n >= 1 && n <= 21 +} + +func pathWindowDays(window string) (int, bool) { + switch window { + case "", "7d", "24h": + return 7, true + case "30d": + return 30, true + } + return 0, false +} + +func checkPair(from, to string) (string, string, error) { + from, to = strings.ToLower(strings.TrimSpace(from)), strings.ToLower(strings.TrimSpace(to)) + if !pubkeyRe.MatchString(from) || !pubkeyRe.MatchString(to) { + return "", "", fmt.Errorf("from and to must both be repeater public keys (64 hex characters)") + } + if from == to { + return "", "", fmt.Errorf("from and to must be two different repeaters") + } + return from, to, nil +} + +// handleDataPath is GET /api/data/path?from=&to=&window=&basis=. +func (s *Server) handleDataPath(w http.ResponseWriter, r *http.Request) { + if !s.pathOr404(w) { + return + } + q := r.URL.Query() + from, to, err := checkPair(q.Get("from"), q.Get("to")) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + days, ok := pathWindowDays(q.Get("window")) + flag, okFlag := pathFlagDays(q.Get("flagDays")) + basis := q.Get("basis") + if !ok || !okFlag || (basis != "" && basis != "all" && basis != "adverts") { + http.Error(w, "window must be 24h, 7d or 30d, flagDays 1 to 21 and basis all or adverts", http.StatusBadRequest) + return + } + writeJSON(w, s.pathWatch(from, to, q.Get("window"), days, flag, basis == "adverts")) +} + +// handleDataPaths is POST /api/data/paths: several pairs in one go, for a +// watch list. +func (s *Server) handleDataPaths(w http.ResponseWriter, r *http.Request) { + if !s.pathOr404(w) { + return + } + var req DataPathsRequest + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&req); err != nil { + http.Error(w, "the body must be {window, basis, pairs: [{from, to}]}", http.StatusBadRequest) + return + } + days, ok := pathWindowDays(req.Window) + if req.FlagDays == 0 { + req.FlagDays = 7 + } + if req.FlagDays < 1 || req.FlagDays > 21 { + ok = false + } + if !ok || (req.Basis != "" && req.Basis != "all" && req.Basis != "adverts") || len(req.Pairs) == 0 || len(req.Pairs) > pathMaxPairs { + http.Error(w, fmt.Sprintf("window must be 24h, 7d or 30d, basis all or adverts, and 1 to %d pairs", pathMaxPairs), http.StatusBadRequest) + return + } + out := DataPathsResponse{Paths: []DataPathResponse{}} + for _, p := range req.Pairs { + from, to, err := checkPair(p.From, p.To) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + out.Paths = append(out.Paths, s.pathWatch(from, to, req.Window, days, req.FlagDays, req.Basis == "adverts")) + } + writeJSON(w, out) +} + +// pathWatch answers one pair, from the cache when it is fresh. +func (s *Server) pathWatch(from, to, window string, days, flagDays int, adverts bool) DataPathResponse { + key := fmt.Sprint(from, to, days, flagDays, adverts) + c := s.pathCacheFor() + c.mu.Lock() + if hit, ok := c.m[key]; ok && time.Since(hit.at) < pathCacheFor { + c.mu.Unlock() + return hit.resp + } + c.mu.Unlock() + + now := time.Now().UTC() + back := max(days+pathBaseDays, flagDays+14) + 1 + since := now.Add(-time.Duration(back) * 24 * time.Hour) + passed, crossings := s.paths.packets(from, to, since, adverts) + reached := make([]pathwatch.Crossing, len(crossings)) + for i, c := range crossings { + reached[i] = pathwatch.Crossing{At: c.at, Route: c.route} + } + act := &indexActivity{idx: s.paths, db: s.db, relays: map[string][]time.Time{}} + res := pathwatch.Analyse(pathwatch.Input{Now: now, Passed: passed, Reached: reached}, act, pathwatch.Options{WindowDays: days, BaseDays: pathBaseDays, FlagDays: flagDays}) + resp := s.pathResponse(from, to, window, adverts, res) + + c.mu.Lock() + if len(c.m) >= pathCacheMax { + var oldest string + for k, v := range c.m { + if oldest == "" || v.at.Before(c.m[oldest].at) { + oldest = k + } + } + delete(c.m, oldest) + } + c.m[key] = pathCached{at: time.Now(), resp: resp} + c.mu.Unlock() + return resp +} + +func parseTxTime(v string) (time.Time, bool) { + for _, layout := range []string{time.RFC3339Nano, "2006-01-02 15:04:05", "2006-01-02T15:04:05", "2006-01-02"} { + if t, err := time.Parse(layout, v); err == nil { + return t.UTC(), true + } + } + return time.Time{}, false +} + +// indexActivity tells pathwatch what a repeater does beyond the path. +type indexActivity struct { + idx *pathIndex + db *DB + relays map[string][]time.Time // sorted, per repeater, read once per request +} + +func (a *indexActivity) Relays(pk string, from, to time.Time) int { + ts, ok := a.relays[pk] + if !ok { + ts = a.idx.relays(pk) + a.relays[pk] = ts + } + lo := sort.Search(len(ts), func(i int) bool { return !ts[i].Before(from) }) + hi := sort.Search(len(ts), func(i int) bool { return !ts[i].Before(to) }) + return hi - lo +} + +func (a *indexActivity) FirstHeard(pk string) (time.Time, bool) { + if a.db == nil || a.db.conn == nil { + return time.Time{}, false + } + var v string + if a.db.conn.QueryRow(`SELECT COALESCE(first_seen,'') FROM nodes WHERE LOWER(public_key) = ?`, pk).Scan(&v) != nil { + return time.Time{}, false + } + return parseTxTime(v) +} + +// nodeNames names repeaters by key; unknown ones are shown by their key's start. +func (s *Server) nodeNames(keys []string) map[string]string { + out := map[string]string{} + if len(keys) == 0 || s.db == nil || s.db.conn == nil { + return out + } + args := make([]interface{}, len(keys)) + for i, k := range keys { + args[i] = k + } + rows, err := s.db.conn.Query(`SELECT LOWER(public_key), COALESCE(name,'') FROM nodes WHERE LOWER(public_key) IN (?`+strings.Repeat(",?", len(keys)-1)+`)`, args...) + if err != nil { + return out + } + defer rows.Close() + for rows.Next() { + var k, n string + if rows.Scan(&k, &n) == nil && n != "" { + out[k] = n + } + } + return out +} + +func (s *Server) pathResponse(from, to, window string, adverts bool, res pathwatch.Result) DataPathResponse { + keys := map[string]bool{from: true, to: true} + for _, r := range res.Routes { + for _, pk := range r.Via { + keys[pk] = true + } + } + for _, c := range res.Changes { + keys[c.Node] = true + for _, pk := range append(append([]string{}, c.From...), c.To...) { + keys[pk] = true + } + } + list := make([]string, 0, len(keys)) + for k := range keys { + if k != "" { + list = append(list, k) + } + } + names := s.nodeNames(list) + node := func(pk string) DataPathNode { + n := names[pk] + if n == "" { + n = pk[:min(8, len(pk))] + } + return DataPathNode{Key: pk, Name: n} + } + nodes := func(pks []string) []DataPathNode { + out := make([]DataPathNode, len(pks)) + for i, pk := range pks { + out[i] = node(pk) + } + return out + } + basis := "all" + if adverts { + basis = "adverts" + } + resp := DataPathResponse{From: node(from), To: node(to), Window: window, Basis: basis, Days: []DataPathDay{}, Share: res.Share, Usual: res.Usual, + Low: res.Low, High: res.High, Verdict: res.Verdict, Hops: res.Hops, Routes: []DataPathRoute{}, Changes: []DataPathChange{}} + for _, d := range res.Days { + resp.Days = append(resp.Days, DataPathDay{Day: d.Day.Format(time.RFC3339), Passed: d.Passed, Reached: d.Reached, Share: d.Share}) + } + for _, r := range res.Routes { + resp.Routes = append(resp.Routes, DataPathRoute{Via: nodes(r.Via), Share: r.Share, Usual: r.Usual}) + } + change := func(c pathwatch.Change) DataPathChange { + out := DataPathChange{Day: c.Day.Format(time.RFC3339), Kind: c.Kind, Was: c.Was, Now: c.Now, From: nodes(c.From), To: nodes(c.To), ShareWas: c.ShareWas, ShareNow: c.ShareNow} + if c.Node != "" { + n := node(c.Node) + out.Node = &n + } + out.Text = changeText(out) + return out + } + for _, c := range res.Changes { + resp.Changes = append(resp.Changes, change(c)) + } + if res.Flag != nil { + f := change(*res.Flag) + resp.Flag = &f + } + return resp +} + +func pct(v float64) string { return fmt.Sprintf("%.0f%%", v*100) } + +func viaText(ns []DataPathNode) string { + if len(ns) == 0 { + return "straight across" + } + names := make([]string, len(ns)) + for i, n := range ns { + names[i] = n.Name + } + return "via " + strings.Join(names, ", ") +} + +// changeText says a route change in a sentence. +func changeText(c DataPathChange) string { + through := "" + if d := c.ShareNow - c.ShareWas; d <= -0.1 || d >= 0.1 { + through = fmt.Sprintf(" The share getting through went from %s to %s.", pct(c.ShareWas), pct(c.ShareNow)) + } + name := "" + if c.Node != nil { + name = c.Node.Name + } + switch c.Kind { + case pathwatch.KindRepeaterQuiet: + return fmt.Sprintf("%s dropped out of this path (it carried %s) and has gone quiet everywhere.%s", name, pct(c.Was), through) + case pathwatch.KindRerouted: + return fmt.Sprintf("%s dropped out of this path (it carried %s) but is still relaying elsewhere, so the traffic was rerouted.%s", name, pct(c.Was), through) + case pathwatch.KindNewRepeater: + return fmt.Sprintf("%s now carries %s, up from %s. It was first heard recently: a new repeater sharing the load.%s", name, pct(c.Now), pct(c.Was), through) + case pathwatch.KindSharing: + return fmt.Sprintf("%s now carries %s, up from %s, sharing the load.%s", name, pct(c.Now), pct(c.Was), through) + case pathwatch.KindRouteShare: + way := "down" + if c.Now > c.Was { + way = "up" + } + return fmt.Sprintf("The main route (%s) carried %s of what got through, %s from %s.%s", viaText(c.To), pct(c.Now), way, pct(c.Was), through) + case pathwatch.KindRouteChanged: + return fmt.Sprintf("The main route moved from %s to %s.%s", viaText(c.From), viaText(c.To), through) + } + return c.Kind +} diff --git a/cmd/server/data_path_index.go b/cmd/server/data_path_index.go new file mode 100644 index 000000000..ec9178af5 --- /dev/null +++ b/cmd/server/data_path_index.go @@ -0,0 +1,415 @@ +package main + +// The path watch's own history: for every packet of the last data.pathDays +// days, when it was first heard and each distinct resolved path its +// observers saw, with repeaters as small numbers. It is independent of the +// packet store, whose window is often shorter (a 14-day flag needs three +// weeks: the fortnight and the week before each change), and it keeps every +// observation's path, not only the longest, so a packet one observer saw +// reach the second repeater counts even when another heard a longer path. +// +// Filled from SQLite after the Data tab's own index (which waits for the +// packet store), topped up every two minutes from new observations, and +// rebuilt once a day so old packets fall away. Read-only. + +import ( + "context" + "database/sql" + "encoding/json" + "log" + "sort" + "strings" + "sync" + "time" +) + +const ( + pathIndexBatch = 5000 + pathIndexRefresh = 2 * time.Minute + pathIndexRebuild = 24 * time.Hour +) + +// pathTx is one packet. Its paths are stored flat, each ended by pathEnd, +// keeping only the longest: a path that is an unbroken stretch of another +// the packet already has says nothing new about where it went. +type pathTx struct { + at uint32 // first heard, unix seconds + from nodeID // the repeater an advert came from; noNode for none + advert bool // payload type 4 + hops []nodeID +} + +// nodeID numbers repeaters in two bytes: a mesh has thousands, not tens of +// thousands. Past maxNodes new repeaters are not named (they count as an +// unresolved hop) rather than wrapping. +type nodeID uint16 + +const ( + noNode nodeID = 0xFFFF // an unresolved hop + pathEnd nodeID = 0xFFFE // ends each path in pathTx.hops + maxNodes = 0xFFFD +) + +type pathIndex struct { + db *DB + days int + waitFor []<-chan struct{} + now func() time.Time + + mu sync.RWMutex + keys []string // id -> lower-case public key + ids map[string]nodeID // public key -> id + txs []pathTx + recent map[int64]int32 // transmission id -> index into txs, for the last two days (late observations) + byNode map[nodeID][]uint32 // repeater -> packets (indexes into txs) with it on a path, or adverts from it + lastObs int64 + built time.Time + ready bool +} + +func newPathIndex(db *DB, days int) *pathIndex { + return &pathIndex{db: db, days: days, now: time.Now, ids: map[string]nodeID{}, recent: map[int64]int32{}, byNode: map[nodeID][]uint32{}} +} + +func (p *pathIndex) isReady() bool { + p.mu.RLock() + defer p.mu.RUnlock() + return p.ready +} + +func (p *pathIndex) run(ctx context.Context) { + for _, ch := range p.waitFor { + select { + case <-ch: + case <-ctx.Done(): + return + } + } + start := time.Now() + if err := p.fill(ctx); err != nil { + log.Printf("[path] fill failed: %v", err) + } else { + p.mu.RLock() + n := len(p.txs) + p.mu.RUnlock() + log.Printf("[path] %d packets over %d days in %s", n, p.days, time.Since(start).Round(time.Millisecond)) + } + tick := time.NewTicker(pathIndexRefresh) + defer tick.Stop() + for { + select { + case <-ctx.Done(): + return + case <-tick.C: + } + var err error + if time.Since(p.built) >= pathIndexRebuild { + err = p.fill(ctx) + } else { + err = p.read(ctx, p, true) + } + if err != nil { + log.Printf("[path] refresh failed: %v", err) + } + } +} + +// fill builds a fresh index of the window and swaps it in. +func (p *pathIndex) fill(ctx context.Context) error { + fresh := newPathIndex(p.db, p.days) + fresh.now = p.now + if err := p.read(ctx, fresh, false); err != nil { + return err + } + fresh.trim() + p.mu.Lock() + p.keys, p.ids, p.txs, p.recent, p.byNode, p.lastObs = fresh.keys, fresh.ids, fresh.txs, fresh.recent, fresh.byNode, fresh.lastObs + p.built, p.ready = time.Now(), true + p.mu.Unlock() + return nil +} + +// read adds the observations into dst: the whole window when it is fresh, +// else those newer than the last read (locked, as dst is then live). +func (p *pathIndex) read(ctx context.Context, dst *pathIndex, live bool) error { + cutoff := p.now().Add(-time.Duration(p.days) * 24 * time.Hour).Unix() + last := dst.lastObs + if live { + dst.mu.RLock() + last = dst.lastObs + dst.mu.RUnlock() + } + for { + if err := ctx.Err(); err != nil { + return err + } + rows, err := p.db.conn.QueryContext(ctx, `SELECT o.id, o.transmission_id, o.timestamp, COALESCE(o.resolved_path,''), t.first_seen, + COALESCE(t.payload_type,-1), COALESCE(t.from_pubkey,'') + FROM observations o JOIN transmissions t ON t.id = o.transmission_id + WHERE o.id > ? AND o.timestamp >= ? ORDER BY o.id LIMIT ?`, last, cutoff, pathIndexBatch) + if err != nil { + return err + } + type row struct { + tx, ts int64 + rp, first string + typ int + from string + } + var batch []row + for rows.Next() { + var id int64 + var r row + var rp sql.NullString + if err := rows.Scan(&id, &r.tx, &r.ts, &rp, &r.first, &r.typ, &r.from); err != nil { + rows.Close() + return err + } + r.rp = rp.String + last = id + batch = append(batch, r) + } + rows.Close() + if live { + dst.mu.Lock() + } + for _, r := range batch { + dst.add(r.tx, r.ts, r.first, r.typ, r.from, r.rp) + } + dst.lastObs = last + done := len(batch) < pathIndexBatch + if done { + dst.forgetOld() + } + if live { + dst.mu.Unlock() + } + if done { + return nil + } + time.Sleep(5 * time.Millisecond) // leave room for requests while filling + } +} + +func (p *pathIndex) id(pk string) nodeID { + if id, ok := p.ids[pk]; ok { + return id + } + if len(p.keys) >= maxNodes { + return noNode + } + id := nodeID(len(p.keys)) + p.keys = append(p.keys, pk) + p.ids[pk] = id + return id +} + +// trim gives back the spare capacity slices grew while filling. +func (p *pathIndex) trim() { + p.txs = append([]pathTx(nil), p.txs...) + for n, l := range p.byNode { + p.byNode[n] = append([]uint32(nil), l...) + } +} + +// forgetOld drops packets more than two days old from the recent map: +// observations of them no longer arrive. +func (p *pathIndex) forgetOld() { + cut := uint32(p.now().Add(-48 * time.Hour).Unix()) + for id, i := range p.recent { + if p.txs[i].at < cut { + delete(p.recent, id) + } + } +} + +// add records one observation. Caller holds the lock on a live index. +func (p *pathIndex) add(txID, ts int64, firstSeen string, typ int, from, rp string) { + i, ok := p.recent[txID] + if !ok { + at := ts + if t, ok := parseTxTime(firstSeen); ok { + at = t.Unix() + } + p.txs = append(p.txs, pathTx{at: uint32(at), from: noNode, advert: typ == advertPayload}) + i = int32(len(p.txs) - 1) + p.recent[txID] = i // trimmed to the last two days once a fill or refresh is read + if p.txs[i].advert && from != "" { + if f := p.id(strings.ToLower(from)); f != noNode { + p.txs[i].from = f + p.byNode[f] = append(p.byNode[f], uint32(i)) + } + } + } + if rp == "" { + return + } + var raw []*string + if json.Unmarshal([]byte(rp), &raw) != nil || len(raw) == 0 { + return + } + path := make([]nodeID, len(raw)) + for k, s := range raw { + path[k] = noNode + if s != nil && *s != "" { + path[k] = p.id(strings.ToLower(*s)) + } + } + tx := &p.txs[i] + on := map[nodeID]bool{} + if tx.from != noNode { + on[tx.from] = true + } + var keep [][]nodeID + covered := false + eachPath(tx.hops, func(q []nodeID) { + for _, n := range q { + on[n] = true + } + switch { + case covered: + keep = append(keep, q) + case stretchOf(path, q): + covered = true // already have a path that holds this one + keep = append(keep, q) + case stretchOf(q, path): + // the new path holds this one: drop it + default: + keep = append(keep, q) + } + }) + if covered { + return + } + keep = append(keep, path) + flat := make([]nodeID, 0, len(tx.hops)+len(path)+1) + for _, q := range keep { + flat = append(append(flat, q...), pathEnd) + } + tx.hops = flat + for _, n := range path { + if n != noNode && !on[n] { + on[n] = true + p.byNode[n] = append(p.byNode[n], uint32(i)) + } + } +} + +// eachPath calls fn with each path stored flat in hops. +func eachPath(hops []nodeID, fn func([]nodeID)) { + start := 0 + for k, n := range hops { + if n == pathEnd { + fn(hops[start:k]) + start = k + 1 + } + } +} + +// stretchOf says whether a is an unbroken stretch of b. +func stretchOf(a, b []nodeID) bool { + if len(a) > len(b) { + return false + } + for off := 0; off+len(a) <= len(b); off++ { + if equalPath(a, b[off:off+len(a)]) { + return true + } + } + return false +} + +func equalPath(a, b []nodeID) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// packets returns when each packet that passed from (or was an advert from +// it) since since was first heard, and the ones some observer saw reach to +// after from, with the repeaters between (from the longest such path). +func (p *pathIndex) packets(from, to string, since time.Time, advertsOnly bool) ([]time.Time, []pathCrossing) { + p.mu.RLock() + defer p.mu.RUnlock() + a, okA := p.ids[from] + b, okB := p.ids[to] + if !okA { + return nil, nil + } + var passed []time.Time + var reached []pathCrossing + lo := uint32(since.Unix()) + for _, ti := range p.byNode[a] { + tx := &p.txs[ti] + if tx.at < lo || (advertsOnly && !tx.advert) { + continue + } + at := time.Unix(int64(tx.at), 0).UTC() + passed = append(passed, at) + if !okB { + continue + } + var best []nodeID + found := false + eachPath(tx.hops, func(path []nodeID) { + ia := -1 + if tx.from != a { + ia = indexOf(path, a, 0) + if ia < 0 { + return + } + } + if ib := indexOf(path, b, ia+1); ib >= 0 { + if seg := path[ia+1 : ib]; !found || len(seg) > len(best) { + best, found = seg, true + } + } + }) + if found { + route := make([]string, 0, len(best)) + for _, n := range best { + if n != noNode { + route = append(route, p.keys[n]) + } + } + reached = append(reached, pathCrossing{at: at, route: route}) + } + } + return passed, reached +} + +func indexOf(path []nodeID, n nodeID, from int) int { + for i := from; i < len(path); i++ { + if path[i] == n { + return i + } + } + return -1 +} + +// relays is when each packet with pk on a path was first heard, sorted. +func (p *pathIndex) relays(pk string) []time.Time { + p.mu.RLock() + defer p.mu.RUnlock() + id, ok := p.ids[pk] + if !ok { + return nil + } + out := make([]time.Time, 0, len(p.byNode[id])) + for _, ti := range p.byNode[id] { + out = append(out, time.Unix(int64(p.txs[ti].at), 0)) + } + sort.Slice(out, func(i, j int) bool { return out[i].Before(out[j]) }) + return out +} + +type pathCrossing struct { + at time.Time + route []string +} diff --git a/cmd/server/data_path_test.go b/cmd/server/data_path_test.go new file mode 100644 index 000000000..be73a1799 --- /dev/null +++ b/cmd/server/data_path_test.go @@ -0,0 +1,283 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gorilla/mux" +) + +const ( + pwGoyle = "a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1" + pwKeir = "b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2" + pwWard = "c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3" + pwInsh = "d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4d4" + pwOther = "e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5" +) + +// pathWatchRouter seeds 20 days: each day 20 packets pass Goyle Hill, Keir +// Hill and Insheswood in that order, and Keir Hill relays its own traffic; +// in the last 24 hours Keir Hill is silent, and only 5 of Goyle Hill's 20 +// reach Insheswood, through Ward Hill. +func pathWatchRouter(t *testing.T, enabled bool) *mux.Router { + t.Helper() + db := setupTestDB(t) + now := time.Now().UTC() + for _, n := range [][3]string{{pwGoyle, "Goyle Hill", "2026-01-01"}, {pwKeir, "Keir Hill", "2026-01-01"}, {pwWard, "Ward Hill", "2026-01-01"}, {pwInsh, "Insheswood", "2026-01-01"}, {pwOther, "Other", "2026-01-01"}} { + mustExec(t, db, `INSERT INTO nodes (public_key, name, role, lat, lon, last_seen, first_seen, advert_count) VALUES (?, ?, 'repeater', 57, -3, ?, ?, 1)`, n[0], n[1], now.Format(time.RFC3339), n[2]) + } + id := 0 + add := func(at time.Time, path ...string) { + id++ + raw := make([]string, len(path)) + for i, p := range path { + raw[i] = strings.ToUpper(p[:6]) + } + rj, _ := json.Marshal(raw) + pj, _ := json.Marshal(path) + mustExec(t, db, `INSERT INTO transmissions (id, raw_hex, hash, first_seen, payload_type) VALUES (?, 'AA', ?, ?, 5)`, id, fmt.Sprintf("h%06d", id), at.Format("2006-01-02T15:04:05.000Z")) + mustExec(t, db, `INSERT INTO observations (transmission_id, observer_idx, path_json, timestamp, resolved_path) VALUES (?, NULL, ?, ?, ?)`, id, string(rj), at.Unix(), string(pj)) + } + for d := 19; d >= 0; d-- { + for k := 0; k < 20; k++ { + at := now.Add(-time.Duration(d+1)*24*time.Hour + time.Duration(k)*time.Hour + time.Minute) + switch { + case d > 0: + add(at, pwGoyle, pwKeir, pwInsh) + add(at.Add(time.Minute), pwKeir, pwOther) + case k < 5: + add(at, pwGoyle, pwWard, pwInsh) + default: + add(at, pwGoyle, pwOther) + } + } + } + return pathRouterFor(t, db, enabled) +} + +// pathRouterFor serves the path watch over db, its index filled. +func pathRouterFor(t *testing.T, db *DB, enabled bool) *mux.Router { + t.Helper() + cfg := &Config{Port: 3000} + if enabled { + cfg.Data = &DataConfig{Enabled: true, Days: 7, PathDays: 30} + } + srv := NewServer(db, cfg, NewHub()) + if enabled { + srv.paths = newPathIndex(db, cfg.PathDays()) + if err := srv.paths.fill(context.Background()); err != nil { + t.Fatal(err) + } + } + r := mux.NewRouter() + r.HandleFunc("/api/data/path", srv.handleDataPath).Methods("GET") + r.HandleFunc("/api/data/paths", srv.handleDataPaths).Methods("POST") + return r +} + +func TestDataPathFollowsTwoRepeatersAndFlagsARepeaterGoneQuiet(t *testing.T) { + r := pathWatchRouter(t, true) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/data/path?from="+pwGoyle+"&to="+pwInsh+"&window=7d", nil)) + if w.Code != 200 { + t.Fatalf("status %d %s", w.Code, w.Body.String()) + } + var p DataPathResponse + if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil { + t.Fatal(err) + } + if p.From.Name != "Goyle Hill" || p.To.Name != "Insheswood" || len(p.Days) != 7 { + t.Fatalf("from %+v to %+v days %d", p.From, p.To, len(p.Days)) + } + if last := p.Days[len(p.Days)-1]; last.Passed != 20 || last.Reached != 5 { + t.Errorf("last 24 h %+v, want 5 of 20", last) + } + if p.Share != 0.25 || p.Usual != 1 || p.Verdict != "worse" { + t.Errorf("share %v usual %v verdict %q", p.Share, p.Usual, p.Verdict) + } + if len(p.Routes) == 0 || p.Routes[0].Via[0].Name != "Keir Hill" { + t.Errorf("routes %+v, want Keir Hill first", p.Routes) + } + if p.Flag == nil || p.Flag.Kind != "repeater-quiet" || p.Flag.Node == nil || p.Flag.Node.Name != "Keir Hill" || + !strings.Contains(p.Flag.Text, "Keir Hill dropped out of this path") || !strings.Contains(p.Flag.Text, "gone quiet") { + t.Errorf("flag %+v, want Keir Hill gone quiet", p.Flag) + } +} + +func TestDataPathsAnswersSeveralPairsAtOnce(t *testing.T) { + r := pathWatchRouter(t, true) + body, _ := json.Marshal(DataPathsRequest{Window: "7d", Pairs: []DataPathPair{{From: pwGoyle, To: pwInsh}, {From: pwInsh, To: pwGoyle}}}) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("POST", "/api/data/paths", bytes.NewReader(body))) + if w.Code != 200 { + t.Fatalf("status %d %s", w.Code, w.Body.String()) + } + var out DataPathsResponse + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { + t.Fatal(err) + } + if len(out.Paths) != 2 || out.Paths[0].Share != 0.25 || out.Paths[1].Days[len(out.Paths[1].Days)-1].Reached != 0 { + t.Fatalf("paths %+v", out.Paths) + } +} + +func TestDataPathIsOffWithTheDataTabAndChecksItsInput(t *testing.T) { + off := pathWatchRouter(t, false) + w := httptest.NewRecorder() + off.ServeHTTP(w, httptest.NewRequest("GET", "/api/data/path?from="+pwGoyle+"&to="+pwInsh, nil)) + if w.Code != 404 { + t.Errorf("off: status %d, want 404", w.Code) + } + on := pathWatchRouter(t, true) + for _, q := range []string{"?from=" + pwGoyle, "?from=zz&to=" + pwInsh, "?from=" + pwGoyle + "&to=" + pwGoyle} { + w := httptest.NewRecorder() + on.ServeHTTP(w, httptest.NewRequest("GET", "/api/data/path"+q, nil)) + if w.Code != 400 { + t.Errorf("%s: status %d, want 400", q, w.Code) + } + } +} + +func TestDashboardsTakeWatchPanelsAndRepeaterVariables(t *testing.T) { + d := Dashboard{Schema: 1, ID: "links", Title: "Links we watch", + Variables: []DashboardVariable{{Name: "from", Kind: "repeater"}, {Name: "to", Kind: "repeater"}}, + Panels: []DashboardPanel{ + {ID: "one", Title: "One link", Type: "watch", Query: DashboardQuery{From: "$from", To: "$to"}, Layout: DashboardLayout{W: 12, H: 6}}, + {ID: "all", Title: "Watches", Type: "watchlist", Options: &DashboardPanelOptions{Watches: []DashboardWatch{{Name: "North link", From: pwGoyle, To: pwInsh, Both: true}}}, Layout: DashboardLayout{Y: 6, W: 12, H: 5}}, + }} + if err := validateDashboard(d); err != nil { + t.Fatalf("valid watch dashboard refused: %v", err) + } + bad := d + bad.Panels = []DashboardPanel{{ID: "one", Title: "One link", Type: "watch", Query: DashboardQuery{From: pwGoyle}, Layout: DashboardLayout{W: 6, H: 4}}} + if validateDashboard(bad) == nil { + t.Error("a watch without both repeaters was accepted") + } + bad.Panels = []DashboardPanel{{ID: "all", Title: "Watches", Type: "watchlist", Options: &DashboardPanelOptions{Watches: []DashboardWatch{{Name: "x", From: "nothex", To: pwInsh}}}, Layout: DashboardLayout{W: 6, H: 4}}} + if validateDashboard(bad) == nil { + t.Error("a watch with a bad key was accepted") + } +} + +// A built-in "Path" dashboard follows any two repeaters picked at the top, +// with or without areas. +func TestThePathDashboardIsBuiltIn(t *testing.T) { + for _, places := range []bool{true, false} { + var path *Dashboard + for _, d := range builtInDashboards(places) { + if d.ID == "path" { + d := d + path = &d + } + } + if path == nil { + t.Fatalf("places=%v: no built-in path dashboard", places) + } + if err := validateDashboard(*path); err != nil { + t.Fatalf("places=%v: %v", places, err) + } + if len(path.Variables) != 2 || path.Variables[0].Kind != "repeater" || path.Panels[0].Type != "watch" || path.Panels[0].Query.From != "$from" { + t.Errorf("places=%v: %+v", places, path) + } + } +} + +// A packet counts as getting through when any observer saw it pass the first +// repeater and then the second, not only the observer with the longest path. +func TestDataPathCountsEveryObservation(t *testing.T) { + db := setupTestDB(t) + now := time.Now().UTC() + for _, k := range []string{pwGoyle, pwInsh, pwOther, pwWard} { + mustExec(t, db, `INSERT INTO nodes (public_key, name, role, first_seen) VALUES (?, 'n', 'repeater', '2026-01-01')`, k) + } + id := 0 + for d := 9; d >= 0; d-- { + for k := 0; k < 12; k++ { + id++ + at := now.Add(-time.Duration(d+1)*24*time.Hour + time.Duration(k)*time.Hour + time.Minute) + mustExec(t, db, `INSERT INTO transmissions (id, raw_hex, hash, first_seen, payload_type) VALUES (?, 'AA', ?, ?, 5)`, id, fmt.Sprintf("e%06d", id), at.Format("2006-01-02T15:04:05.000Z")) + long, _ := json.Marshal([]string{pwGoyle, pwOther, pwWard, pwOther}) + short, _ := json.Marshal([]string{pwGoyle, pwInsh}) + mustExec(t, db, `INSERT INTO observations (transmission_id, observer_idx, path_json, timestamp, resolved_path) VALUES (?, 1, '["A1","E5","C3","E5"]', ?, ?)`, id, at.Unix(), string(long)) + mustExec(t, db, `INSERT INTO observations (transmission_id, observer_idx, path_json, timestamp, resolved_path) VALUES (?, 2, '["A1","D4"]', ?, ?)`, id, at.Unix(), string(short)) + } + } + r := pathRouterFor(t, db, true) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/data/path?from="+pwGoyle+"&to="+pwInsh, nil)) + var p DataPathResponse + if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil { + t.Fatal(err, w.Body.String()) + } + if p.Share != 1 { + t.Errorf("share %v, want every packet counted (the shorter observation reached Insheswood)", p.Share) + } +} + +// History reaches back past what the packet store holds: a change ten days +// ago is still the flag when flags last a fortnight. +func TestDataPathRemembersAFortnight(t *testing.T) { + db := setupTestDB(t) + now := time.Now().UTC() + for _, n := range [][2]string{{pwGoyle, "Goyle Hill"}, {pwKeir, "Keir Hill"}, {pwWard, "Ward Hill"}, {pwInsh, "Insheswood"}} { + mustExec(t, db, `INSERT INTO nodes (public_key, name, role, first_seen) VALUES (?, ?, 'repeater', '2026-01-01')`, n[0], n[1]) + } + id := 0 + for d := 25; d >= 0; d-- { + for k := 0; k < 20; k++ { + id++ + at := now.Add(-time.Duration(d+1)*24*time.Hour + time.Duration(k)*time.Hour + time.Minute) + via := pwKeir + if d <= 10 { + via = pwWard + } + pj, _ := json.Marshal([]string{pwGoyle, via, pwInsh}) + mustExec(t, db, `INSERT INTO transmissions (id, raw_hex, hash, first_seen, payload_type) VALUES (?, 'AA', ?, ?, 5)`, id, fmt.Sprintf("f%06d", id), at.Format("2006-01-02T15:04:05.000Z")) + mustExec(t, db, `INSERT INTO observations (transmission_id, observer_idx, path_json, timestamp, resolved_path) VALUES (?, 1, '["A1","B2","D4"]', ?, ?)`, id, at.Unix(), string(pj)) + } + } + r := pathRouterFor(t, db, true) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/data/path?from="+pwGoyle+"&to="+pwInsh+"&flagDays=14", nil)) + var p DataPathResponse + if err := json.Unmarshal(w.Body.Bytes(), &p); err != nil { + t.Fatal(err, w.Body.String()) + } + if p.Flag == nil || p.Flag.Node == nil || p.Flag.Node.Name != "Keir Hill" { + t.Fatalf("flag %+v, want Keir Hill dropping out ten days ago", p.Flag) + } + w = httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/data/path?from="+pwGoyle+"&to="+pwInsh+"&flagDays=99", nil)) + if w.Code != 400 { + t.Errorf("flagDays=99: status %d, want 400", w.Code) + } +} + +// Observations of one packet read days later (a fill of old history) still +// make one packet, not one per observation. +func TestPathIndexCountsPacketsNotObservations(t *testing.T) { + db := setupTestDB(t) + at := time.Now().UTC().Add(-10 * 24 * time.Hour) + mustExec(t, db, `INSERT INTO transmissions (id, raw_hex, hash, first_seen, payload_type) VALUES (1, 'AA', 'p1', ?, 5)`, at.Format("2006-01-02T15:04:05.000Z")) + for i, rp := range []string{`["` + pwGoyle + `"]`, `["` + pwGoyle + `","` + pwInsh + `"]`, `["` + pwKeir + `"]`} { + mustExec(t, db, `INSERT INTO observations (transmission_id, observer_idx, path_json, timestamp, resolved_path) VALUES (1, ?, '[]', ?, ?)`, i+1, at.Unix(), rp) + } + idx := newPathIndex(db, 21) + if err := idx.fill(context.Background()); err != nil { + t.Fatal(err) + } + if len(idx.txs) != 1 || len(idx.recent) != 0 { + t.Fatalf("packets %d, recent %d; want one packet, none recent", len(idx.txs), len(idx.recent)) + } + n := 0 + eachPath(idx.txs[0].hops, func([]nodeID) { n++ }) + if n != 2 { + t.Errorf("paths kept %d, want 2 (Goyle alone is a stretch of Goyle, Insheswood)", n) + } +} diff --git a/cmd/server/data_places_test.go b/cmd/server/data_places_test.go new file mode 100644 index 000000000..ea635ada8 --- /dev/null +++ b/cmd/server/data_places_test.go @@ -0,0 +1,153 @@ +package main + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/meshcore-analyzer/dataindex" +) + +// placeDims are the dimensions that need areas to mean anything. +var placeDims = map[string]bool{"border": true, "origin": true, "heard": true, "through": true, "how": true} + +// placelessFixture is the data fixture's database with the Data tab on and +// no areas at all: an operator who does not want to draw a GeoJSON file. +func placelessFixture(t *testing.T) *dataFixture { + t.Helper() + f := newDataFixture(t, false) + f.cfg = &Config{Data: &DataConfig{Enabled: true}} + svc, err := newDataService(f.db, f.cfg) + if err != nil { + t.Fatalf("enabled with no areas: %v, want the tab on without places", err) + } + if svc == nil { + t.Fatal("enabled with no areas gave no service") + } + now := f.now + svc.now = func() time.Time { return now } + f.svc = svc + return f +} + +func TestDataTabRunsWithoutAreas(t *testing.T) { + f := placelessFixture(t) + if err := f.svc.fill(context.Background()); err != nil { + t.Fatal(err) + } + // One row per packet: nothing is placed, so every packet is heard in one + // "unknown" area and started in it. + if n := f.svc.index().Len(); n != 2 { + t.Errorf("index rows = %d, want 2 (p1 and p2, each once)", n) + } + res := f.svc.packets("7d", 0, 0, nil) + if res.Total != 2 || len(res.Rows) != 2 { + t.Errorf("packets = %d (%d rows), want both packets listed", res.Total, len(res.Rows)) + } + cube := f.svc.index().Cube(dataindex.Window{Key: "7d", Span: 7 * 24 * time.Hour, Bucket: time.Hour}, f.now) + n := 0 + for _, r := range cube.Rows { + n += r[9] + } + if n != 2 { + t.Errorf("cube counts %d packets, want 2: with no areas every row is a packet, not a placeholder", n) + } + for _, r := range res.Rows { + if r.Origin != dataindex.Unknown || r.Heard != dataindex.Unknown { + t.Errorf("%s: origin %q heard %q, want both unknown with no areas", r.Hash, r.Origin, r.Heard) + } + } +} + +func TestDataConfigWithoutAreasOffersNoPlaces(t *testing.T) { + f := placelessFixture(t) + if err := f.svc.fill(context.Background()); err != nil { + t.Fatal(err) + } + // Read as the browser does: a field this build lacks is simply absent. + var cfg struct { + Enabled bool `json:"enabled"` + Places *bool `json:"places"` + Home string `json:"home"` + Areas []any `json:"areas"` + Dimensions []string `json:"dimensions"` + } + if code := getJSON(t, dataRouter(f), "/api/data/config", &cfg); code != 200 { + t.Fatalf("config = %d", code) + } + if !cfg.Enabled || cfg.Places == nil || *cfg.Places { + t.Errorf("enabled %v places %v, want on, with places reported false", cfg.Enabled, cfg.Places) + } + if len(cfg.Areas) != 0 || cfg.Home != "" { + t.Errorf("areas %v home %q, want none", cfg.Areas, cfg.Home) + } + want := []string{"kind", "type", "channel", "scope", "sclass", "routing"} + if strings.Join(cfg.Dimensions, ",") != strings.Join(want, ",") { + t.Errorf("dimensions = %v, want %v", cfg.Dimensions, want) + } + // With areas the place dimensions are offered and places is true. + g := newDataFixture(t, true) + full := cfg + full.Places = nil + getJSON(t, dataRouter(g), "/api/data/config", &full) + if full.Places == nil || !*full.Places || len(full.Dimensions) != len(dataindex.Dimensions) { + t.Errorf("with areas: places %v dimensions %v, want true and all of them", full.Places, full.Dimensions) + } +} + +func TestBuiltInDashboardsWithoutAreasLeavePlacesOut(t *testing.T) { + ds, err := LoadDataDashboards(&Config{Data: &DataConfig{Enabled: true}}, t.TempDir()) + if err != nil { + t.Fatal(err) + } + if len(ds.Dashboards) == 0 { + t.Fatal("no built-in dashboards without areas") + } + for _, d := range ds.Dashboards { + if len(d.Panels) == 0 { + t.Errorf("%s has no panels left", d.ID) + } + for _, p := range d.Panels { + q := p.Query + for _, dim := range []string{q.X, q.Split, q.Facet, q.Rows, q.Cols, q.Dim} { + if placeDims[dim] { + t.Errorf("%s/%s uses %q with no areas", d.ID, p.ID, dim) + } + } + for _, fl := range q.Filters { + if placeDims[fl.D] { + t.Errorf("%s/%s filters on %q with no areas", d.ID, p.ID, fl.D) + } + } + } + } +} + +func TestOperatorDashboardsNeedAreasForPlaces(t *testing.T) { + cases := map[string]string{ + "a place dimension": `[{"schema":1,"id":"x","title":"X","panels":[{"id":"a","title":"A","type":"top","query":{"dim":"heard"},"layout":{"x":0,"y":0,"w":4,"h":4}}]}]`, + "a place filter": `[{"schema":1,"id":"x","title":"X","panels":[{"id":"a","title":"A","type":"stat","query":{"filters":[{"d":"border","n":0,"v":["crossed"]}]},"layout":{"x":0,"y":0,"w":4,"h":2}}]}]`, + "an area variable": `[{"schema":1,"id":"x","title":"X","variables":[{"name":"home","kind":"area"}],"panels":[]}]`, + } + for name, body := range cases { + dir := writeDashboards(t, body) + _, err := LoadDataDashboards(&Config{Data: &DataConfig{Enabled: true, DashboardsFile: "dashboards.json"}}, dir) + if err == nil || !strings.Contains(err.Error(), "needs areas") { + t.Errorf("%s with no areas: err %v, want one saying it needs areas", name, err) + } + } + // The same scope-only dashboard loads fine. + dir := writeDashboards(t, `[{"schema":1,"id":"x","title":"X","panels":[{"id":"a","title":"A","type":"top","query":{"dim":"scope"},"layout":{"x":0,"y":0,"w":4,"h":4}}]}]`) + if _, err := LoadDataDashboards(&Config{Data: &DataConfig{Enabled: true, DashboardsFile: "dashboards.json"}}, dir); err != nil { + t.Errorf("scope-only dashboard with no areas: %v", err) + } +} + +func TestHomeAreaNeedsAreas(t *testing.T) { + f := newDataFixture(t, false) + _, err := newDataService(f.db, &Config{Data: &DataConfig{Enabled: true, HomeArea: "SCO"}}) + if err == nil || !strings.Contains(err.Error(), "needs areas") { + t.Errorf("homeArea with no areas: err %v, want one saying it needs areas", err) + } +} diff --git a/cmd/server/data_startup_test.go b/cmd/server/data_startup_test.go new file mode 100644 index 000000000..cdce462d9 --- /dev/null +++ b/cmd/server/data_startup_test.go @@ -0,0 +1,67 @@ +package main + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// The Data tab's 7-day fill must not run on top of the packet store's +// startup load: together they pushed a 1.5 GB container over its limit +// every time the background fill reached its subpath index, about 50 s +// after each start, and the server was OOM-killed in a loop. The fill waits +// for the store's startup-load-done signal; until then the tab says it is +// filling (503) rather than "not enabled" (404). +func TestDataFillWaitsForTheStartupLoad(t *testing.T) { + f := newDataFixture(t, true) + loaded := make(chan struct{}) + f.svc.waitFor = loaded + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go f.svc.run(ctx) + + time.Sleep(150 * time.Millisecond) + if f.svc.index() != nil { + t.Fatal("the fill started before the startup load finished") + } + var cfg struct { + Filling bool `json:"filling"` + } + r := dataRouter(f) + getJSON(t, r, "/api/data/config", &cfg) + if !cfg.Filling { + t.Error("while waiting, /api/data/config should report filling") + } + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/data/cube?window=24h", nil)) + if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "filling") { + t.Errorf("cube while waiting = %d %q, want 503 saying it is filling", w.Code, w.Body.String()) + } + + close(loaded) + deadline := time.Now().Add(5 * time.Second) + for f.svc.index() == nil && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if f.svc.index() == nil { + t.Fatal("the fill did not start once the startup load finished") + } +} + +// Without a signal (tests, or no packet store) the fill starts at once. +func TestDataFillStartsAtOnceWithoutASignal(t *testing.T) { + f := newDataFixture(t, true) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go f.svc.run(ctx) + deadline := time.Now().Add(5 * time.Second) + for f.svc.index() == nil && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if f.svc.index() == nil { + t.Fatal("the fill never started") + } +} diff --git a/cmd/server/data_test.go b/cmd/server/data_test.go new file mode 100644 index 000000000..dfa749532 --- /dev/null +++ b/cmd/server/data_test.go @@ -0,0 +1,301 @@ +package main + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "testing" + "time" + + "github.com/gorilla/mux" +) + +// Two areas with real-ish edges: SCO above 55°N, IOI west of 5.5°W below it. +const dataAreasGeoJSON = `{"type":"FeatureCollection","features":[ + {"type":"Feature","properties":{"code":"SCO","label":"Scotland","layer":"country","iata":["EDI"]}, + "geometry":{"type":"Polygon","coordinates":[[[-8,55.0],[-0.5,55.0],[-0.5,61],[-8,61],[-8,55.0]]]}}, + {"type":"Feature","properties":{"code":"IOI","label":"Island of Ireland","layer":"country","iata":["NOC"]}, + "geometry":{"type":"Polygon","coordinates":[[[-11,51],[-5.5,51],[-5.5,55.0],[-11,55.0],[-11,51]]]}} +]}` + +type dataFixture struct { + db *DB + cfg *Config + svc *dataService + now time.Time +} + +func dataTS(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000Z") } + +// newDataFixture seeds a mesh of two repeaters (Edinburgh, Belfast) and two +// observers (one in Edinburgh, one placed only by its airport code), with +// three packets: two in the last day and one older than the index reaches. +func newDataFixture(t *testing.T, enabled bool) *dataFixture { + t.Helper() + db := setupTestDB(t) + mustExecDB(t, db, `ALTER TABLE transmissions ADD COLUMN scope_name TEXT`) + db.hasScopeName = true + now := time.Now().UTC().Truncate(time.Second) + for _, q := range []string{ + `INSERT INTO nodes (public_key, name, role, lat, lon) VALUES ('AA11110000000000000000000000000000000000000000000000000000000000', 'Edinburgh Rpt', 'repeater', 55.95, -3.19)`, + `INSERT INTO nodes (public_key, name, role, lat, lon) VALUES ('CC33330000000000000000000000000000000000000000000000000000000000', 'Belfast Rpt', 'repeater', 54.60, -5.93)`, + `INSERT INTO nodes (public_key, name, role, lat, lon) VALUES ('0B5E000000000000000000000000000000000000000000000000000000000000', 'Edinburgh Obs', 'repeater', 55.94, -3.20)`, + `INSERT INTO observers (id, name, iata) VALUES ('0B5E000000000000000000000000000000000000000000000000000000000000', 'Edinburgh Obs', 'EDI')`, + `INSERT INTO observers (id, name, iata) VALUES ('OBSNOC', 'Knock', 'NOC')`, + } { + mustExecDB(t, db, q) + } + // p1: a Scottish channel message on #sco, heard at home and in Ireland. + // p2: an Irish advert with its own position, heard in Edinburgh. + // p3: ten days old, outside a 7-day index. + tx := func(id int, hash string, at time.Time, typ, route int, scope any, decoded string) { + t.Helper() + if _, err := db.conn.Exec(`INSERT INTO transmissions (id, raw_hex, hash, first_seen, route_type, payload_type, decoded_json, scope_name) VALUES (?, '00', ?, ?, ?, ?, ?, ?)`, + id, hash, dataTS(at), route, typ, decoded, scope); err != nil { + t.Fatal(err) + } + } + obs := func(txID, observerIdx int, path, resolved string) { + t.Helper() + if _, err := db.conn.Exec(`INSERT INTO observations (transmission_id, observer_idx, direction, path_json, resolved_path, timestamp) VALUES (?, ?, 'rx', ?, ?, ?)`, + txID, observerIdx, path, resolved, now.Unix()); err != nil { + t.Fatal(err) + } + } + tx(1, "00000000000000p1", now.Add(-2*time.Hour), 5, 0, "#sco", `{"channel":"Public"}`) + obs(1, 1, `["AA11"]`, `["AA11110000000000000000000000000000000000000000000000000000000000"]`) + obs(1, 2, `["AA11","CC33"]`, ``) + tx(2, "00000000000000a2", now.Add(-time.Hour), 4, 1, nil, `{"pubKey":"FFEE","lat":54.6,"lon":-5.9,"flags":{"hasLocation":true}}`) + obs(2, 1, `["CC33","AA11"]`, ``) + tx(3, "00000000000000a3", now.Add(-10*24*time.Hour), 2, 1, nil, `{}`) + obs(3, 1, `["AA11"]`, ``) + + dir := writeAreasFile(t, dataAreasGeoJSON) + cfg := &Config{AreasFile: "areas.geojson", Data: &DataConfig{Enabled: enabled, HomeArea: "SCO"}} + if _, err := LoadAreaMap(cfg, dir); err != nil { + t.Fatal(err) + } + svc, err := newDataService(db, cfg) + if err != nil { + t.Fatal(err) + } + if svc != nil { + svc.now = func() time.Time { return now } + } + return &dataFixture{db: db, cfg: cfg, svc: svc, now: now} +} + +func TestDataConfigDefaults(t *testing.T) { + var c *Config = &Config{} + if c.DataEnabled() || c.DataDays() != 7 { + t.Errorf("no data block: enabled %v days %d, want off and 7", c.DataEnabled(), c.DataDays()) + } + c.Data = &DataConfig{Enabled: true, Days: 90} + if c.DataDays() != 30 { + t.Errorf("days 90 = %d, want capped at 30", c.DataDays()) + } + c.Data.Days = -1 + if c.DataDays() != 7 { + t.Errorf("days -1 = %d, want 7", c.DataDays()) + } +} + +// Enabled with no areas is a Data tab without places: data_places_test.go. +func TestDataServiceIsOffUnlessEnabled(t *testing.T) { + f := newDataFixture(t, false) + if f.svc != nil { + t.Error("data.enabled false should give no service") + } +} + +func TestDataServiceFillsFromSQLite(t *testing.T) { + f := newDataFixture(t, true) + if err := f.svc.fill(context.Background()); err != nil { + t.Fatal(err) + } + ix := f.svc.index() + // p1 heard in SCO and IOI, p2 heard in SCO; p3 is too old. + if ix.Len() != 3 { + t.Fatalf("index rows = %d, want 3", ix.Len()) + } + if c := ix.Covered(); c == 0 || c > f.now.Add(-7*24*time.Hour+time.Minute).Unix() { + t.Errorf("covered from %v, want the full 7 days", time.Unix(c, 0)) + } + res := f.svc.packets("7d", 0, 0, nil) + byHeard := map[string]string{} + for _, r := range res.Rows { + byHeard[r.Hash+"@"+r.Heard] = r.Origin + "/" + r.Basis + "/" + r.Scope + "/" + r.Channel + "/" + r.How + } + want := map[string]string{ + "00000000000000p1@SCO": "SCO/first-relay/#sco/Public/relayed", + "00000000000000p1@IOI": "SCO/first-relay/#sco/Public/relayed", + "00000000000000a2@SCO": "IOI/advert/unscoped//relayed", + } + for k, v := range want { + if byHeard[k] != v { + t.Errorf("%s = %q, want %q", k, byHeard[k], v) + } + } + // Relays are named from the node table. + for _, r := range res.Rows { + if r.Hash == "00000000000000p1" && r.Heard == "IOI" && r.HeardFrom != "Belfast Rpt" { + t.Errorf("p1 in IOI heard from %q, want Belfast Rpt", r.HeardFrom) + } + } +} + +func TestDataRefreshPicksUpLateObservations(t *testing.T) { + f := newDataFixture(t, true) + ctx := context.Background() + if err := f.svc.fill(ctx); err != nil { + t.Fatal(err) + } + // Knock hears p2 late. + mustExecDB(t, f.db, `INSERT INTO observations (transmission_id, observer_idx, direction, path_json, timestamp) VALUES (2, 2, 'rx', '["CC33"]', 0)`) + // A brand new packet arrives. + if _, err := f.db.conn.Exec(`INSERT INTO transmissions (id, raw_hex, hash, first_seen, route_type, payload_type, decoded_json) VALUES (4, '00', '00000000000000a4', ?, 1, 2, '{}')`, dataTS(f.now.Add(-time.Minute))); err != nil { + t.Fatal(err) + } + mustExecDB(t, f.db, `INSERT INTO observations (transmission_id, observer_idx, direction, path_json, timestamp) VALUES (4, 1, 'rx', '["AA11"]', 0)`) + f.svc.refreshSpan = 2 * time.Hour + if err := f.svc.refresh(ctx); err != nil { + t.Fatal(err) + } + if n := f.svc.index().Len(); n != 5 { + t.Errorf("rows after refresh = %d, want 5 (p2 now also heard in IOI, a4 new)", n) + } +} + +func dataRouter(f *dataFixture) *mux.Router { + srv := &Server{db: f.db, cfg: f.cfg, data: f.svc} + r := mux.NewRouter() + r.HandleFunc("/api/data/config", srv.handleDataConfig).Methods("GET") + r.HandleFunc("/api/data/summary", srv.handleDataSummary).Methods("GET") + r.HandleFunc("/api/data/cube", srv.handleDataCube).Methods("GET") + r.HandleFunc("/api/data/packets", srv.handleDataPackets).Methods("GET") + return r +} + +func getJSON(t *testing.T, r http.Handler, path string, into any) int { + t.Helper() + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + if into != nil && w.Code == http.StatusOK { + if err := json.NewDecoder(w.Body).Decode(into); err != nil { + t.Fatalf("%s: %v", path, err) + } + } + return w.Code +} + +func TestDataEndpointsWhenDisabled(t *testing.T) { + f := newDataFixture(t, false) + r := dataRouter(f) + var cfg map[string]any + if code := getJSON(t, r, "/api/data/config", &cfg); code != 200 || cfg["enabled"] != false { + t.Errorf("config = %d %v, want 200 and enabled false", code, cfg) + } + for _, p := range []string{"/api/data/summary?window=24h", "/api/data/cube?window=24h", "/api/data/packets?window=24h"} { + if code := getJSON(t, r, p, nil); code != http.StatusNotFound { + t.Errorf("%s = %d, want 404 while disabled", p, code) + } + } +} + +func TestDataEndpoints(t *testing.T) { + f := newDataFixture(t, true) + if err := f.svc.fill(context.Background()); err != nil { + t.Fatal(err) + } + r := dataRouter(f) + + var cfg struct { + Enabled bool `json:"enabled"` + Layer string `json:"layer"` + Home string `json:"home"` + Areas []struct { + Code, Label string + } `json:"areas"` + Windows []struct{ Key string } `json:"windows"` + Groups []struct{ Key string } `json:"groups"` + Days int `json:"days"` + Rows int `json:"rows"` + } + if code := getJSON(t, r, "/api/data/config", &cfg); code != 200 { + t.Fatalf("config = %d", code) + } + if !cfg.Enabled || cfg.Layer != "country" || cfg.Home != "SCO" || cfg.Days != 7 || cfg.Rows != 3 { + t.Errorf("config = %+v", cfg) + } + if len(cfg.Areas) != 2 || cfg.Areas[0].Code != "SCO" || cfg.Areas[0].Label != "Scotland" { + t.Errorf("areas = %+v, want SCO then IOI with labels", cfg.Areas) + } + if len(cfg.Windows) != 2 || cfg.Windows[0].Key != "24h" || cfg.Windows[1].Key != "7d" { + t.Errorf("windows = %+v, want 24h and 7d for a 7-day index", cfg.Windows) + } + if len(cfg.Groups) != 3 { + t.Errorf("groups = %+v", cfg.Groups) + } + + var cube struct { + Rows [][10]int `json:"rows"` + Heard []string `json:"heard"` + Origins []string `json:"origins"` + } + if code := getJSON(t, r, "/api/data/cube?window=7d", &cube); code != 200 { + t.Fatalf("cube = %d", code) + } + total := 0 + for _, x := range cube.Rows { + total += x[9] + } + if total != 3 || len(cube.Heard) != 2 { + t.Errorf("cube total %d heard %v, want 3 over SCO and IOI", total, cube.Heard) + } + if code := getJSON(t, r, "/api/data/cube?window=30d", nil); code != http.StatusBadRequest { + t.Errorf("a window past the index = %d, want 400", code) + } + + var sum struct { + Packets int `json:"packets"` + CrossBorder int `json:"crossBorder"` + } + if code := getJSON(t, r, "/api/data/summary?window=24h", &sum); code != 200 || sum.Packets != 2 || sum.CrossBorder != 2 { + t.Errorf("summary = %d %+v, want 2 packets, both crossing", code, sum) + } + + var pk struct { + Total int `json:"total"` + Rows []struct { + Hash string `json:"hash"` + Heard string `json:"heard"` + } `json:"rows"` + } + f1 := url.QueryEscape(`[{"d":"heard","v":["IOI"]}]`) + if code := getJSON(t, r, "/api/data/packets?window=7d&f="+f1, &pk); code != 200 || pk.Total != 1 || pk.Rows[0].Hash != "00000000000000p1" { + t.Errorf("packets heard in IOI = %d %+v", code, pk) + } + if code := getJSON(t, r, "/api/data/packets?window=7d&f=notjson", nil); code != http.StatusBadRequest { + t.Errorf("bad filter = %d, want 400", code) + } + if code := getJSON(t, r, `/api/data/packets?window=7d&f=`+url.QueryEscape(`[{"d":"nosuch","v":["x"]}]`), nil); code != http.StatusBadRequest { + t.Errorf("unknown dimension = %d, want 400", code) + } +} + +func TestDataCubeIsCachedAndBuiltOnce(t *testing.T) { + f := newDataFixture(t, true) + if err := f.svc.fill(context.Background()); err != nil { + t.Fatal(err) + } + a, err := f.svc.cubeJSON("7d") + if err != nil { + t.Fatal(err) + } + b, _ := f.svc.cubeJSON("7d") + if &a[0] != &b[0] { + t.Error("a second request inside the cache time should reuse the first answer") + } +} diff --git a/cmd/server/db.go b/cmd/server/db.go index b396a266d..864cd8fc9 100644 --- a/cmd/server/db.go +++ b/cmd/server/db.go @@ -15,6 +15,7 @@ import ( "time" _ "github.com/mattn/go-sqlite3" + "github.com/meshcore-analyzer/dataindex" "github.com/meshcore-analyzer/dbschema" "github.com/meshcore-analyzer/geofilter" "github.com/meshcore-analyzer/packetpath" @@ -712,6 +713,9 @@ type PacketQuery struct { Channel string // channel_hash filter (#812). Plain names like "#test"/"public" or "enc_" for encrypted Order string // ASC or DESC ExpandObservations bool // when true, include observation sub-maps in txToMap output + // startedIn, when set, decides Area by where each packet started (the + // Data tab's index) instead of by the advert sender's position. + startedIn func(hash string) bool } // PacketResult wraps paginated packet list. @@ -720,6 +724,9 @@ type PacketResult struct { Total int `json:"total"` Limit int `json:"limit"` Offset int `json:"offset"` + // Origins says where each listed packet started, when the Data tab + // places packets in areas. + Origins map[string]dataindex.Origin `json:"origins,omitempty"` } // QueryPackets returns paginated, filtered packets as transmissions (matching Node.js shape). @@ -3190,6 +3197,10 @@ func (db *DB) GetNodePubkeysInArea(entry AreaEntry) ([]string, error) { LonMin: entry.LonMin, LonMax: entry.LonMax, } + inside := func(lat, lon float64) bool { return geofilter.PassesFilter(lat, lon, gf) } + if entry.match != nil { + inside = entry.match + } var result []string for rows.Next() { @@ -3205,7 +3216,7 @@ func (db *DB) GetNodePubkeysInArea(entry AreaEntry) ([]string, error) { if lat.Float64 == 0 && lon.Float64 == 0 { continue } - if geofilter.PassesFilter(lat.Float64, lon.Float64, gf) { + if inside(lat.Float64, lon.Float64) { result = append(result, pk) } } @@ -3223,6 +3234,23 @@ func (db *DB) GetSignatureDropCount() int64 { return count } +// scopeStatsByRegionQuery counts named-region transport transmissions in the +// window, per region. +// +// The unary + on every scope_name reference keeps SQLite off +// idx_tx_scope_name: with it, the planner walked every scoped transmission in +// the database (every non-empty scope_name) and filtered by time afterwards, 2.5-2.9 s on +// a production database whatever the window. The window is the selective +// condition, so the query searches idx_transmissions_first_seen and groups in a +// temp b-tree (same idiom as the advertsByRole query below). +var scopeStatsByRegionQuery = ` + SELECT scope_name, COUNT(*) AS cnt + FROM transmissions + WHERE ` + routeTypeTransportSQL + ` AND +scope_name IS NOT NULL AND +scope_name != '' AND first_seen >= ? + GROUP BY +scope_name + ORDER BY cnt DESC + ` + func (db *DB) GetScopeStats(window string) (*ScopeStatsResponse, error) { if !db.hasScopeName { return nil, fmt.Errorf("scope_name column not present — run ingestor to apply migrations") @@ -3281,13 +3309,7 @@ func (db *DB) GetScopeStats(window string) (*ScopeStatsResponse, error) { resp.Summary.Unscoped += nonTransportUnscoped // Per-region counts (named regions only) - rows, err := db.conn.Query(` - SELECT scope_name, COUNT(*) AS cnt - FROM transmissions - WHERE `+routeTypeTransportSQL+` AND scope_name IS NOT NULL AND scope_name != '' AND first_seen >= ? - GROUP BY scope_name - ORDER BY cnt DESC - `, since) + rows, err := db.conn.Query(scopeStatsByRegionQuery, since) if err != nil { return nil, fmt.Errorf("scope byRegion query: %w", err) } diff --git a/cmd/server/eviction_test.go b/cmd/server/eviction_test.go index cc80bd8c2..c9cfc942c 100644 --- a/cmd/server/eviction_test.go +++ b/cmd/server/eviction_test.go @@ -19,7 +19,7 @@ func makeTestStore(count int, startTime time.Time, intervalMin int) *PacketStore byNode: make(map[string][]*StoreTx), nodeHashes: make(map[string]map[string]bool), byPayloadType: make(map[int][]*StoreTx), - spIndex: make(map[string]int), + spTxIndex: make(map[string][]*StoreTx), distHops: make([]distHopRecord, 0), distPaths: make([]distPathRecord, 0), rfCache: make(map[string]*cachedResult), @@ -84,7 +84,7 @@ func makeTestStore(count int, startTime time.Time, intervalMin int) *PacketStore store.distPaths = append(store.distPaths, distPathRecord{tx: tx, Hash: hash}) // Subpath index - addTxToSubpathIndex(store.spIndex, tx) + addTxToSubpathIndex(store.spTxIndex, tx) // Track bytes for self-accounting store.trackedBytes += rechargeTx(tx) @@ -261,7 +261,7 @@ func TestEvictStale_CleansResolvedPathNodeIndexes(t *testing.T) { byNode: make(map[string][]*StoreTx), nodeHashes: make(map[string]map[string]bool), byPayloadType: make(map[int][]*StoreTx), - spIndex: make(map[string]int), + spTxIndex: make(map[string][]*StoreTx), distHops: make([]distHopRecord, 0), distPaths: make([]distPathRecord, 0), rfCache: make(map[string]*cachedResult), diff --git a/cmd/server/go.mod b/cmd/server/go.mod index badbe96db..4b7000ec6 100644 --- a/cmd/server/go.mod +++ b/cmd/server/go.mod @@ -5,10 +5,22 @@ go 1.22 require ( github.com/gorilla/mux v1.8.1 github.com/gorilla/websocket v1.5.3 + github.com/meshcore-analyzer/areamap v0.0.0 + github.com/meshcore-analyzer/dataindex v0.0.0 + github.com/meshcore-analyzer/pathwatch v0.0.0 + github.com/meshcore-analyzer/origin v0.0.0 github.com/meshcore-analyzer/geofilter v0.0.0 github.com/meshcore-analyzer/sigvalidate v0.0.0 ) +replace github.com/meshcore-analyzer/areamap => ../../internal/areamap + +replace github.com/meshcore-analyzer/dataindex => ../../internal/dataindex + +replace github.com/meshcore-analyzer/pathwatch => ../../internal/pathwatch + +replace github.com/meshcore-analyzer/origin => ../../internal/origin + replace github.com/meshcore-analyzer/geofilter => ../../internal/geofilter replace github.com/meshcore-analyzer/sigvalidate => ../../internal/sigvalidate diff --git a/cmd/server/index_ready_1008.go b/cmd/server/index_ready_1008.go index 64517c9d7..217f1d275 100644 --- a/cmd/server/index_ready_1008.go +++ b/cmd/server/index_ready_1008.go @@ -10,13 +10,13 @@ // - subpathReady / pathHopReady are atomic.Bool flags written exactly // once by the background builder (false → true) and never reset // thereafter. Handlers read them via SubpathIndexReady() / -// PathHopIndexReady() before touching s.spIndex / s.spTxIndex / +// PathHopIndexReady() before touching s.spTxIndex / // s.byPathHop. While a flag is false, the handler responds 503 + // Retry-After: 5. // // - The builder itself acquires s.mu.Lock() and calls the existing // buildSubpathIndex() / buildPathHopIndex() methods. Those methods -// replace s.spIndex / s.spTxIndex / s.byPathHop with freshly- +// replace s.spTxIndex / s.byPathHop with freshly- // allocated maps under the write lock. Visibility of the populated // maps to handlers that see Ready()==true is guaranteed by Go's // sync/atomic acquire-release semantics (formalized in Go 1.19): @@ -29,7 +29,7 @@ // ingest serialization). // // - Ingest-side incremental updates in StoreNewTransmissions / -// pruning / hash-collision paths continue to write s.spIndex / +// pruning / hash-collision paths continue to write // s.spTxIndex / s.byPathHop directly under s.mu.Lock(). Because // the builder also runs under s.mu.Lock() and the builder // overwrites whatever is there, the brief window between Load() @@ -91,7 +91,7 @@ func writeIndexLoading503(w http.ResponseWriter) { // SubpathIndexReady reports whether the subpath index build kicked off // by Load() has completed (#1008). Until this returns true, callers -// must NOT read s.spIndex / s.spTxIndex. +// must NOT read s.spTxIndex. func (s *PacketStore) SubpathIndexReady() bool { return s.subpathReady.Load() } @@ -197,7 +197,7 @@ func (s *PacketStore) markIndexesReadySync() { // WaitIndexesReady blocks until both background indexes built by // startBackgroundIndexBuilds() report ready, or the deadline expires. // Returns true if both flipped in time. Intended for tests that read -// s.spIndex / s.spTxIndex / s.byPathHop directly after Load(); production +// s.spTxIndex / s.byPathHop directly after Load(); production // code paths gate via SubpathIndexReady() / PathHopIndexReady() and // respond 503 + Retry-After to clients instead of blocking. // diff --git a/cmd/server/main.go b/cmd/server/main.go index 58a679825..f335ef284 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -105,6 +105,14 @@ func main() { if err != nil { log.Printf("[config] warning: %v (using defaults)", err) } + // Areas from config.json and areasFile. A bad areas file stops startup: + // running with areas silently missing would put packets in the wrong + // place without anyone noticing. + if am, err := LoadAreaMap(cfg, configDir); err != nil { + log.Fatalf("[areas] %v", err) + } else if n := len(am.Areas("")); n > 0 { + log.Printf("[areas] %d areas in layers %v", n, am.Layers()) + } // CLI flags override config if port > 0 { @@ -367,6 +375,34 @@ func main() { srv := NewServer(database, cfg, hub) srv.configDir = configDir srv.store = store + // The Data tab's index (off unless data.enabled). A tab switched on with + // nothing to place packets in stops startup rather than serving nothing. + if ds, err := newDataService(database, cfg); err != nil { + log.Fatalf("[data] %v", err) + } else if ds != nil { + dash, derr := LoadDataDashboards(cfg, configDir) + if derr != nil { + log.Fatalf("[data] %v", derr) + } + ds.dashboards = dash + log.Printf("[data] %d dashboards, opening on %q", len(dash.Dashboards), dash.Default) + srv.data = ds + if store != nil { + ds.waitFor = store.StartupLoadDone() + } + // The path watch's history fills after the Data tab's first fill + // (which itself waits for the packet store), never alongside it. + ds.firstFill = make(chan struct{}) + srv.paths = newPathIndex(database, cfg.PathDays()) + srv.paths.waitFor = []<-chan struct{}{ds.firstFill} + go srv.paths.run(context.Background()) + go ds.run(context.Background()) + if ds.places() { + log.Printf("[data] Data tab on: layer %q, %d days", ds.layer, ds.days) + } else { + log.Printf("[data] Data tab on without areas (no places): %d days", ds.days) + } + } // Optional user management (off by default). Fails startup on a bad // config rather than running with registration that cannot work. if err := srv.initUserManagement(resolvedDB); err != nil { diff --git a/cmd/server/neighbor_graph_test.go b/cmd/server/neighbor_graph_test.go index e9a02cc73..45e3a4ac7 100644 --- a/cmd/server/neighbor_graph_test.go +++ b/cmd/server/neighbor_graph_test.go @@ -35,7 +35,7 @@ func ngTestStore(nodes []nodeInfo, packets []*StoreTx) *PacketStore { chanCache: make(map[string]*cachedResult), distCache: make(map[string]*cachedResult), subpathCache: make(map[string]*cachedResult), - spIndex: make(map[string]int), + spTxIndex: make(map[string][]*StoreTx), } ps.nodeCache = nodes ps.nodePM = buildPrefixMap(nodes) diff --git a/cmd/server/nodes_response_cache_test.go b/cmd/server/nodes_response_cache_test.go new file mode 100644 index 000000000..4fffde0db --- /dev/null +++ b/cmd/server/nodes_response_cache_test.go @@ -0,0 +1,212 @@ +package main + +import ( + "fmt" + "io" + "log" + "net/http" + "net/http/httptest" + "os" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/mux" +) + +// /api/nodes builds every node row into a map, enriches it and encodes the +// page on every request: on one production instance that was 95 GB of +// allocation over 45 hours (about 6.7 MB per request), a quarter of all bytes +// allocated. The same few queries repeat (three paginated pages of one query +// were 10,000 of 14,000 requests in a day), so identical queries inside +// nodesResponseTTL share one built and encoded response. + +func getNodes(t *testing.T, router http.Handler, url string) string { + t.Helper() + req := httptest.NewRequest("GET", url, nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != 200 { + t.Fatalf("GET %s: %d %s", url, w.Code, w.Body.String()) + } + return w.Body.String() +} + +func countNodeBuilds(srv *Server) *int32 { + var n int32 + srv.nodesComputeHook = func() { atomic.AddInt32(&n, 1) } + return &n +} + +func TestHandleNodes_IdenticalQueryBuiltOnce(t *testing.T) { + srv, router := setupTestServer(t) + builds := countNodeBuilds(srv) + a := getNodes(t, router, "/api/nodes?limit=50") + b := getNodes(t, router, "/api/nodes?limit=50") + if got := atomic.LoadInt32(builds); got != 1 { + t.Fatalf("expected one build for two identical queries, got %d", got) + } + if a != b { + t.Fatal("cached response differs from the built one") + } +} + +func TestHandleNodes_ParameterOrderSharesEntry(t *testing.T) { + srv, router := setupTestServer(t) + builds := countNodeBuilds(srv) + getNodes(t, router, "/api/nodes?limit=50&offset=0") + getNodes(t, router, "/api/nodes?offset=0&limit=50") + if got := atomic.LoadInt32(builds); got != 1 { + t.Fatalf("expected reordered parameters to share one build, got %d", got) + } +} + +func TestHandleNodes_DistinctQueriesBuiltSeparately(t *testing.T) { + srv, router := setupTestServer(t) + builds := countNodeBuilds(srv) + a := getNodes(t, router, "/api/nodes?limit=50") + b := getNodes(t, router, "/api/nodes?limit=1") + if got := atomic.LoadInt32(builds); got != 2 { + t.Fatalf("expected two builds for two different queries, got %d", got) + } + if a == b { + t.Fatal("different limits returned the same body") + } +} + +func TestHandleNodes_ConcurrentMissesShareOneBuild(t *testing.T) { + srv, router := setupTestServer(t) + var n int32 + srv.nodesComputeHook = func() { + atomic.AddInt32(&n, 1) + time.Sleep(50 * time.Millisecond) // make sure the callers overlap + } + var wg sync.WaitGroup + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { defer wg.Done(); getNodes(t, router, "/api/nodes?limit=50") }() + } + wg.Wait() + if got := atomic.LoadInt32(&n); got != 1 { + t.Fatalf("expected 10 concurrent identical requests to share one build, got %d", got) + } +} + +func TestHandleNodes_RebuiltAfterTTL(t *testing.T) { + srv, router := setupTestServer(t) + builds := countNodeBuilds(srv) + getNodes(t, router, "/api/nodes?limit=50") + srv.expireNodesCacheForTest() + getNodes(t, router, "/api/nodes?limit=50") + if got := atomic.LoadInt32(builds); got != 2 { + t.Fatalf("expected a rebuild once the cached response expired, got %d builds", got) + } +} + +func TestHandleNodes_GeoFilterChangeDropsCache(t *testing.T) { + srv, router := setupTestServer(t) + builds := countNodeBuilds(srv) + getNodes(t, router, "/api/nodes?limit=50") + srv.setGeoFilter(&GeoFilterConfig{Polygon: [][2]float64{{0, 0}, {0, 1}, {1, 1}}}) + getNodes(t, router, "/api/nodes?limit=50") + if got := atomic.LoadInt32(builds); got != 2 { + t.Fatalf("expected a geo-filter change to drop cached node pages, got %d builds", got) + } +} + +// expireNodesCacheForTest drops every cached /api/nodes response. +func (s *Server) expireNodesCacheForTest() { s.invalidateNodesCache() } + +// nodesBenchServer serves 1,100 nodes (a production instance lists about +// 1,085), half of them repeaters. +func nodesBenchServer(b *testing.B) http.Handler { + b.Helper() + log.SetOutput(io.Discard) + b.Cleanup(func() { log.SetOutput(os.Stderr) }) + db := setupTestDB(b) + now := time.Now().UTC() + for i := 0; i < 1100; i++ { + role := "companion" + if i%2 == 0 { + role = "repeater" + } + seen := now.Add(-time.Duration(i%720) * time.Hour).Format(time.RFC3339) + if _, err := db.conn.Exec(`INSERT INTO nodes (public_key, name, role, lat, lon, last_seen, first_seen, advert_count) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + fmt.Sprintf("%064x", i+1000), fmt.Sprintf("Bench node %d", i), role, + 55+float64(i%100)/50, -4+float64(i%80)/40, seen, seen, i%50); err != nil { + b.Fatal(err) + } + } + srv := NewServer(db, &Config{Port: 3000}, NewHub()) + store := NewPacketStore(db, nil) + if err := store.Load(); err != nil { + b.Fatal(err) + } + store.WaitIndexesReady(5 * time.Second) + srv.store = store + router := mux.NewRouter() + srv.RegisterRoutes(router) + return router +} + +func benchGet(b *testing.B, router http.Handler, url string) { + req := httptest.NewRequest("GET", url, nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != 200 { + b.Fatalf("GET %s: %d", url, w.Code) + } +} + +// BenchmarkHandleNodesRepeated: the production pattern, one query asked over +// and over (the top query was 3,378 of 14,053 requests in a day). +func BenchmarkHandleNodesRepeated(b *testing.B) { + router := nodesBenchServer(b) + const url = "/api/nodes?limit=500&offset=0&lastHeard=30d" + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchGet(b, router, url) + } +} + +// BenchmarkHandleNodesUnique: every request a different query, so nothing is +// served from cache; shows the miss path does not get slower. +func BenchmarkHandleNodesUnique(b *testing.B) { + router := nodesBenchServer(b) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchGet(b, router, fmt.Sprintf("/api/nodes?limit=500&offset=0&lastHeard=30d&search=&n=%d", i)) + } +} + +func TestHandleNodes_FilterListChangesMissCache(t *testing.T) { + srv, router := setupTestServer(t) + builds := countNodeBuilds(srv) + getNodes(t, router, "/api/nodes?limit=50") + srv.cfg.SetHiddenNamePrefixes([]string{"zz-hidden"}) + getNodes(t, router, "/api/nodes?limit=50") + srv.cfg.SetNodeBlacklist([]string{"0000000000000000"}) + getNodes(t, router, "/api/nodes?limit=50") + if got := atomic.LoadInt32(builds); got != 3 { + t.Fatalf("expected hidden-prefix and blacklist changes to miss the cache, got %d builds", got) + } +} + +func TestNodesCache_BoundedByBytes(t *testing.T) { + srv := &Server{} + body := make([]byte, nodesCacheMaxBytes/5) // under the per-entry limit + for i := 0; i < 20; i++ { + srv.storeNodesResponse(fmt.Sprintf("q%d", i), body) + if srv.nodesCacheBytes > nodesCacheMaxBytes { + t.Fatalf("cache holds %d bytes after %d inserts, limit %d", srv.nodesCacheBytes, i+1, nodesCacheMaxBytes) + } + } + srv.storeNodesResponse("huge", make([]byte, nodesCacheMaxBytes/4+1)) + if _, ok := srv.cachedNodesResponse("huge"); ok { + t.Fatal("expected an oversized response not to be cached") + } +} diff --git a/cmd/server/notify_eval.go b/cmd/server/notify_eval.go index f8e46e65b..d5c9aa4df 100644 --- a/cmd/server/notify_eval.go +++ b/cmd/server/notify_eval.go @@ -53,6 +53,10 @@ type notifyInput struct { // older than this counts as heard at this time, so nothing goes offline // until a full silent window has passed after the feed came back. IngestResumedAt time.Time + // External is the fresh externalAlerts feed; nil when it is not + // configured, nobody chose node.external, or the feed is stale. nil + // leaves every node.external state unchanged. + External *externalFeed } // notifyChange is one transition for one user. @@ -62,6 +66,8 @@ type notifyChange struct { Name string // display name at evaluation time To string // users.NotifyGood, users.NotifyBad or users.NotifyTold BatteryMv *int // node.battery only + Text string // node.external only: the alert text ("" when resolved) + URL string // node.external only: the alert's link, "" for the node page At time.Time } @@ -85,7 +91,8 @@ const ( ) var notifyEventRank = map[string]int{ - users.NotifyNodeOffline: 0, users.NotifyNodeBattery: 1, users.NotifyForeignNew: 2, users.NotifyObserverOffline: 3, + users.NotifyNodeOffline: 0, users.NotifyNodeBattery: 1, users.NotifyNodeExternal: 2, + users.NotifyForeignNew: 3, users.NotifyObserverOffline: 4, } // notifyInfra reports the roles whose relay activity counts as heard @@ -173,6 +180,39 @@ func observerState(o notifyObserver, h HealthThresholds, now, resumed time.Time, return users.NotifyGood } +// evalExternal compares one watched node's current external alerts with the +// stored node.external states of one user. The first fresh feed after the +// node is watched (no baseline row) stores the current alerts silently; +// afterwards a new or returning alert is a bad change and a stored bad alert +// missing from the feed is a good (resolved) change. +func evalExternal(res *notifyResult, prev map[users.NotifyKey]string, bad []string, current map[string]externalAlert, + uid int64, pk, name string, mailing bool, now time.Time) { + base := users.NotifyKey{UserID: uid, Event: users.NotifyNodeExternal, Subject: pk + "/" + externalBaselineKey} + _, baselined := prev[base] + if !baselined { + res.States = append(res.States, users.NotifyState{NotifyKey: base, State: users.NotifyGood, ChangedAt: now}) + } + emit := func(key, state string, a externalAlert) { + k := users.NotifyKey{UserID: uid, Event: users.NotifyNodeExternal, Subject: pk + "/" + key} + res.States = append(res.States, users.NotifyState{NotifyKey: k, State: state, ChangedAt: now}) + if baselined && mailing { + res.Changes[uid] = append(res.Changes[uid], notifyChange{Event: users.NotifyNodeExternal, Subject: k.Subject, + Name: name, To: state, Text: a.Text, URL: a.URL, At: now}) + } + } + for _, key := range sortedExternalKeys(current) { + if prev[users.NotifyKey{UserID: uid, Event: users.NotifyNodeExternal, Subject: pk + "/" + key}] != users.NotifyBad { + emit(key, users.NotifyBad, current[key]) + } + } + sort.Strings(bad) + for _, key := range bad { + if _, still := current[key]; !still { + emit(key, users.NotifyGood, externalAlert{}) + } + } +} + // evaluateNotifications computes every chosen (user, event, subject) state // and compares it with the stored one. A subject without a stored state is // stored without a change (a restart or a new watch never mails); a stored @@ -184,8 +224,18 @@ func observerState(o notifyObserver, h HealthThresholds, now, resumed time.Time, // rows are dropped, like opting out, so a re-promotion starts silently. func evaluateNotifications(in notifyInput) notifyResult { prev := make(map[users.NotifyKey]string, len(in.States)) + // extBad: per user and node, the node.external keys stored as bad. + extBad := map[int64]map[string][]string{} for _, s := range in.States { prev[s.NotifyKey] = s.State + if s.Event == users.NotifyNodeExternal && s.State == users.NotifyBad { + if pk, key, ok := strings.Cut(s.Subject, "/"); ok && key != externalBaselineKey { + if extBad[s.UserID] == nil { + extBad[s.UserID] = map[string][]string{} + } + extBad[s.UserID][pk] = append(extBad[s.UserID][pk], key) + } + } } watched := map[int64][]string{} for _, w := range in.Watches { @@ -254,6 +304,9 @@ func evaluateNotifications(in notifyInput) notifyResult { k := users.NotifyKey{UserID: p.UserID, Event: users.NotifyNodeBattery, Subject: pk} compare(k, name, batteryState(*n.BatteryMv, in.LowMv, prev[k]), n.BatteryMv) } + if p.Has(users.NotifyNodeExternal) && in.External != nil { + evalExternal(&res, prev, extBad[p.UserID][pk], in.External.Alerts[pk], p.UserID, pk, name, mailing, in.Now) + } } if u.Role != users.RoleAdmin { continue diff --git a/cmd/server/notify_external.go b/cmd/server/notify_external.go new file mode 100644 index 000000000..2a4a86eee --- /dev/null +++ b/cmd/server/notify_external.go @@ -0,0 +1,136 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "sort" + "strings" + "time" +) + +// External node alerts (#2177): a JSON feed of per-node alerts that a job +// outside CoreScope computes, e.g. coverage sectors where a repeater is +// never heard. The notifier reads it for the node.external event; the +// server never writes anything for it outside users.db. + +const ( + externalFeedMaxBytes = 1 << 20 + externalFeedTimeout = 10 * time.Second + externalKeyMaxLen = 64 + externalTextMaxLen = 200 + // externalBaselineKey is the subject suffix "/*" that marks a + // user's node.external baseline for one watched node: the first fresh + // feed after watching stores every current alert without mailing; + // afterwards an alert without a row is new. + externalBaselineKey = "*" +) + +// externalFeedJSON is the feed as published. +type externalFeedJSON struct { + GeneratedAt string `json:"generatedAt"` + Alerts []externalAlertJSON `json:"alerts"` +} + +type externalAlertJSON struct { + Pubkey string `json:"pubkey"` + Key string `json:"key"` + Text string `json:"text"` + URL string `json:"url,omitempty"` +} + +// externalAlert is one validated alert. +type externalAlert struct { + Text string // mail-safe + URL string // absolute http(s) or "" +} + +// externalFeed is a validated, fresh feed: alerts by lowercase pubkey, +// then by key. +type externalFeed struct { + GeneratedAt time.Time + Alerts map[string]map[string]externalAlert + Skipped int // malformed entries left out +} + +// parseExternalFeed validates body. It fails when the body does not +// decode, generatedAt is missing, or the feed is older than maxAge at now; +// the caller then treats the source as stale. Malformed alerts are +// skipped and counted; a duplicate (pubkey, key) keeps the first. +func parseExternalFeed(body []byte, now time.Time, maxAge time.Duration) (*externalFeed, error) { + var raw externalFeedJSON + if err := json.Unmarshal(body, &raw); err != nil { + return nil, fmt.Errorf("decode: %w", err) + } + gen, err := time.Parse(time.RFC3339, strings.TrimSpace(raw.GeneratedAt)) + if err != nil { + return nil, errors.New("generatedAt missing or not RFC 3339") + } + if age := now.Sub(gen); age > maxAge { + return nil, fmt.Errorf("generated %s ago, older than %s", age.Round(time.Minute), maxAge) + } + f := &externalFeed{GeneratedAt: gen, Alerts: map[string]map[string]externalAlert{}} + for _, a := range raw.Alerts { + pk, ok := notifyPubkey(a.Pubkey) + key := mailSafeText(a.Key) + text := mailSafeText(a.Text) + if !ok || key == "" || key == externalBaselineKey || len(key) > externalKeyMaxLen || text == "" { + f.Skipped++ + continue + } + if len(text) > externalTextMaxLen { + text = strings.ToValidUTF8(text[:externalTextMaxLen], "") + "..." + } + if f.Alerts[pk] == nil { + f.Alerts[pk] = map[string]externalAlert{} + } + if _, dup := f.Alerts[pk][key]; dup { + f.Skipped++ + continue + } + f.Alerts[pk][key] = externalAlert{Text: text, URL: externalAlertURL(a.URL)} + } + return f, nil +} + +// externalAlertURL keeps an absolute http(s) URL and drops anything else. +func externalAlertURL(raw string) string { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return "" + } + return u.String() +} + +// sortedExternalKeys returns the keys of m in order. +func sortedExternalKeys(m map[string]externalAlert) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +// fetchExternalFeed GETs the feed: 200 only, at most externalFeedMaxBytes. +func fetchExternalFeed(client *http.Client, feedURL string) ([]byte, error) { + resp, err := client.Get(feedURL) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("HTTP %d", resp.StatusCode) + } + body, err := io.ReadAll(io.LimitReader(resp.Body, externalFeedMaxBytes+1)) + if err != nil { + return nil, err + } + if len(body) > externalFeedMaxBytes { + return nil, fmt.Errorf("larger than %d bytes", externalFeedMaxBytes) + } + return body, nil +} diff --git a/cmd/server/notify_external_test.go b/cmd/server/notify_external_test.go new file mode 100644 index 000000000..b5663a5a7 --- /dev/null +++ b/cmd/server/notify_external_test.go @@ -0,0 +1,289 @@ +package main + +import ( + "errors" + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + "github.com/meshcore-analyzer/users" +) + +// Tests for the node.external event and its feed (#2177). + +func extFeed(at time.Time, alerts ...string) []byte { + return []byte(fmt.Sprintf(`{"generatedAt":%q,"alerts":[%s]}`, at.UTC().Format(time.RFC3339), strings.Join(alerts, ","))) +} + +func extAlert(pk, key, text, url string) string { + return fmt.Sprintf(`{"pubkey":%q,"key":%q,"text":%q,"url":%q}`, pk, key, text, url) +} + +func TestParseExternalFeed(t *testing.T) { + long := strings.Repeat("x", externalTextMaxLen+10) + body := extFeed(evNow.Add(-time.Hour), + extAlert(strings.ToUpper(evPkA), "SE", "not heard\nto the south-east", "https://example.org/coverage"), + extAlert(evPkA, "N", long, "javascript:alert(1)"), + extAlert(evPkA, "SE", "duplicate", ""), + extAlert("abc", "SE", "short key", ""), + extAlert(evPkB, "", "no key", ""), + extAlert(evPkB, "*", "reserved key", ""), + extAlert(evPkB, strings.Repeat("k", externalKeyMaxLen+1), "long key", ""), + extAlert(evPkB, "W", " ", ""), + ) + f, err := parseExternalFeed(body, evNow, 48*time.Hour) + if err != nil { + t.Fatal(err) + } + if f.Skipped != 6 || len(f.Alerts) != 1 || len(f.Alerts[evPkA]) != 2 { + t.Fatalf("feed = %+v; want 2 alerts on A and 6 skipped", f) + } + if a := f.Alerts[evPkA]["SE"]; a.Text != "not heard to the south-east" || a.URL != "https://example.org/coverage" { + t.Fatalf("SE = %+v", a) + } + if a := f.Alerts[evPkA]["N"]; a.URL != "" || len(a.Text) != externalTextMaxLen+3 || !strings.HasSuffix(a.Text, "...") { + t.Fatalf("N = %+v; want a truncated text and no URL", a) + } + for name, c := range map[string]struct { + body []byte + want string + }{ + "too old": {extFeed(evNow.Add(-49 * time.Hour)), "older than"}, + "no timestamp": {[]byte(`{"alerts":[]}`), "generatedAt"}, + "not json": {[]byte(``), "decode"}, + } { + if _, err := parseExternalFeed(c.body, evNow, 48*time.Hour); err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("%s: err = %v; want %q", name, err, c.want) + } + } +} + +func TestFetchExternalFeed(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/ok": + fmt.Fprint(w, `{"generatedAt":"2026-10-07T11:00:00Z","alerts":[]}`) + case "/big": + w.Write([]byte(strings.Repeat(" ", externalFeedMaxBytes+1))) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + if body, err := fetchExternalFeed(srv.Client(), srv.URL+"/ok"); err != nil || !strings.Contains(string(body), "generatedAt") { + t.Fatalf("ok = %q, %v", body, err) + } + if _, err := fetchExternalFeed(srv.Client(), srv.URL+"/gone"); err == nil || !strings.Contains(err.Error(), "404") { + t.Errorf("404 = %v", err) + } + if _, err := fetchExternalFeed(srv.Client(), srv.URL+"/big"); err == nil || !strings.Contains(err.Error(), "larger") { + t.Errorf("oversized = %v", err) + } +} + +func TestResolveExternalAlerts(t *testing.T) { + if got, err := resolveExternalAlerts(nil); err != nil || got.url != "" { + t.Fatalf("absent = %+v, %v; want not configured", got, err) + } + got, err := resolveExternalAlerts(&ExternalAlertsConfig{URL: " http://coverage-job/alerts.json "}) + if err != nil || got.url != "http://coverage-job/alerts.json" || got.maxAge != 48*time.Hour || got.label != "External alert" { + t.Fatalf("defaults = %+v, %v", got, err) + } + got, err = resolveExternalAlerts(&ExternalAlertsConfig{URL: "https://x.example/a", MaxAgeHours: 30, Label: " Coverage\n"}) + if err != nil || got.maxAge != 30*time.Hour || got.label != "Coverage" { + t.Fatalf("set = %+v, %v", got, err) + } + for _, bad := range []string{"", "alerts.json", "file:///etc/passwd", "ftp://x/a"} { + if _, err := resolveExternalAlerts(&ExternalAlertsConfig{URL: bad}); err == nil { + t.Errorf("url %q accepted", bad) + } + } +} + +// extInput: evUser watches evPkA with node.external chosen. +func extInput(alerts map[string]map[string]externalAlert) notifyInput { + in := evInput() + in.Prefs = []users.NotifyPrefs{{UserID: evUser, Enabled: true, Events: []string{users.NotifyNodeExternal}}} + in.Nodes[evPkA] = notifyNode{Pubkey: evPkA, Name: "Alpha", Role: "repeater"} + if alerts != nil { + in.External = &externalFeed{GeneratedAt: evNow, Alerts: alerts} + } + return in +} + +func TestEvaluateExternalBaselineThenChanges(t *testing.T) { + se := map[string]map[string]externalAlert{evPkA: {"SE": {Text: "never heard to the SE", URL: "https://example.org/c"}}} + res := evaluateNotifications(extInput(se)) + if len(res.Changes) != 0 { + t.Fatalf("first fresh feed mailed: %+v", res.Changes) + } + if s, ok := evState(res, evUser, users.NotifyNodeExternal, evPkA+"/*"); !ok || s != users.NotifyGood { + t.Fatal("no baseline stored") + } + if s, _ := evState(res, evUser, users.NotifyNodeExternal, evPkA+"/SE"); s != users.NotifyBad { + t.Fatal("current alert not stored as bad") + } + + base := evStateRow(evUser, users.NotifyNodeExternal, evPkA+"/*", users.NotifyGood) + seBad := evStateRow(evUser, users.NotifyNodeExternal, evPkA+"/SE", users.NotifyBad) + + // A new alert after the baseline mails, an unchanged one does not. + in := extInput(map[string]map[string]externalAlert{evPkA: {"SE": se[evPkA]["SE"], "W": {Text: "never heard to the W"}}}) + in.States = []users.NotifyState{base, seBad} + res = evaluateNotifications(in) + want := []notifyChange{{Event: users.NotifyNodeExternal, Subject: evPkA + "/W", Name: "Alpha", To: users.NotifyBad, Text: "never heard to the W", At: evNow}} + if !reflect.DeepEqual(res.Changes[evUser], want) { + t.Fatalf("new alert = %+v; want %+v", res.Changes[evUser], want) + } + + // An alert gone from a fresh feed is resolved. + in = extInput(map[string]map[string]externalAlert{}) + in.States = []users.NotifyState{base, seBad} + res = evaluateNotifications(in) + if c := res.Changes[evUser]; len(c) != 1 || c[0].Subject != evPkA+"/SE" || c[0].To != users.NotifyGood { + t.Fatalf("resolved = %+v", c) + } + + // It comes back: bad again, mailed. + in = extInput(se) + in.States = []users.NotifyState{base, evStateRow(evUser, users.NotifyNodeExternal, evPkA+"/SE", users.NotifyGood)} + if c := evaluateNotifications(in).Changes[evUser]; len(c) != 1 || c[0].To != users.NotifyBad { + t.Fatalf("returning alert = %+v", c) + } +} + +func TestEvaluateExternalStaleFeedChangesNothing(t *testing.T) { + in := extInput(nil) + in.States = []users.NotifyState{ + evStateRow(evUser, users.NotifyNodeExternal, evPkA+"/*", users.NotifyGood), + evStateRow(evUser, users.NotifyNodeExternal, evPkA+"/SE", users.NotifyBad), + } + if res := evaluateNotifications(in); len(res.Changes) != 0 || len(res.States) != 0 { + t.Fatalf("stale feed: changes %+v, states %+v; want neither", res.Changes, res.States) + } +} + +func TestEvaluateExternalOnlyWhenChosenAndQuietWhenOff(t *testing.T) { + se := map[string]map[string]externalAlert{evPkA: {"SE": {Text: "x"}}} + in := extInput(se) + in.Prefs[0].Events = []string{users.NotifyNodeBattery} + if _, ok := evState(evaluateNotifications(in), evUser, users.NotifyNodeExternal, evPkA+"/*"); ok { + t.Fatal("node.external evaluated for a user who did not choose it") + } + in = extInput(se) + in.Prefs[0].Enabled = false + in.States = []users.NotifyState{evStateRow(evUser, users.NotifyNodeExternal, evPkA+"/*", users.NotifyGood)} + res := evaluateNotifications(in) + if len(res.Changes) != 0 { + t.Fatalf("notifications off mailed: %+v", res.Changes) + } + if s, _ := evState(res, evUser, users.NotifyNodeExternal, evPkA+"/SE"); s != users.NotifyBad { + t.Fatal("state not kept current while notifications are off") + } +} + +func TestNotifyExternalChangeTextAndURL(t *testing.T) { + at := time.Date(2026, 10, 7, 9, 5, 0, 0, time.UTC) + bad := notifyChange{Event: users.NotifyNodeExternal, Subject: evPkA + "/SE", Name: "Alpha", To: users.NotifyBad, + Text: "never heard to the south-east", URL: "https://example.org/c", At: at} + if got := notifyChangeText(bad, "Coverage"); got != "Alpha: Coverage: never heard to the south-east, 2026-10-07 09:05 UTC" { + t.Errorf("bad = %q", got) + } + good := notifyChange{Event: users.NotifyNodeExternal, Subject: evPkA + "/SE", Name: "Alpha", To: users.NotifyGood, At: at} + if got := notifyChangeText(good, "Coverage"); got != "Alpha: Coverage resolved (SE), 2026-10-07 09:05 UTC" { + t.Errorf("good = %q", got) + } + if got := notifySubjectURL("https://e.org", bad); got != "https://example.org/c" { + t.Errorf("alert URL = %q", got) + } + if got := notifySubjectURL("https://e.org", good); got != "https://e.org/#/nodes/"+evPkA { + t.Errorf("resolved URL = %q", got) + } +} + +func extNotifySettings() notifySettings { + ns := defaultNotifySettings() + ns.external = externalAlertSettings{url: "http://coverage-job/alerts.json", maxAge: 48 * time.Hour, label: "Coverage"} + return ns +} + +func TestNotifierMailsExternalAlertsAndSkipsAStaleFeed(t *testing.T) { + f := newNotifyFixture(t, extNotifySettings()) + pat := f.watcher(t, "pat@example.org", "Pat", evPkA) + if _, err := f.st.SetNotifyPrefs(pat.me.ID, true, []string{users.NotifyNodeExternal}); err != nil { + t.Fatal(err) + } + f.setNode(evPkA, "Alpha", "repeater", time.Hour, nil) + f.src.feed = extFeed(f.clk.t) + f.tick() + f.src.feed = extFeed(f.clk.t, extAlert(evPkA, "SE", "never heard to the south-east", "https://example.org/c")) + f.tick() + m := f.notifyMails() + if len(m) != 1 || !strings.Contains(m[0].Text, "Alpha: Coverage: never heard to the south-east") || + !strings.Contains(m[0].Text, "https://example.org/c") { + t.Fatalf("mails = %+v", m) + } + // The feed dies: nothing is resolved. + f.src.feed, f.src.feedErr = nil, errors.New("HTTP 502") + f.tick() + f.src.feedErr = nil + f.src.feed = extFeed(f.clk.t.Add(-72 * time.Hour)) + f.tick() + if len(f.notifyMails()) != 1 { + t.Fatal("a failed or old feed mailed") + } + f.src.feed = extFeed(f.clk.t) + f.tick() + if m := f.notifyMails(); len(m) != 2 || !strings.Contains(m[1].Text, "Alpha: Coverage resolved (SE)") { + t.Fatalf("resolved mail = %+v", m) + } +} + +func TestNotifierFetchesTheFeedOnlyWhenChosenAndConfigured(t *testing.T) { + f := newNotifyFixture(t, extNotifySettings()) + f.watcher(t, "pat@example.org", "Pat", evPkA) + f.setNode(evPkA, "Alpha", "repeater", time.Hour, nil) + f.tick() + if f.src.feedAsked != 0 { + t.Fatal("feed fetched although nobody chose node.external") + } + g := newNotifyFixture(t, defaultNotifySettings()) + pat := g.watcher(t, "pat@example.org", "Pat", evPkA) + if _, err := g.st.SetNotifyPrefs(pat.me.ID, true, []string{users.NotifyNodeExternal}); err != nil { + t.Fatal(err) + } + g.setNode(evPkA, "Alpha", "repeater", time.Hour, nil) + g.tick() + if g.src.feedAsked != 0 { + t.Fatal("feed fetched although externalAlerts is not configured") + } +} + +func TestNotifyAccountOffersExternalOnlyWhenConfigured(t *testing.T) { + f := newNotifyFixture(t, defaultNotifySettings()) + pat := f.registerAndActivate(t, "pat@example.org", "Pat", pw) + got := decode[notifyAccountJSON](t, f.do("GET", "/api/account/notifications", nil, as(pat))) + if reflect.DeepEqual(got.AvailableEvents, nil) || got.ExternalLabel != "" || strings.Contains(strings.Join(got.AvailableEvents, ","), "node.external") { + t.Fatalf("not configured = %+v", got) + } + w := f.do("PUT", "/api/account/notifications", notifyPrefsRequest{Enabled: true, Events: []string{"node.external"}}, as(pat)) + if w.Code != 400 || !strings.Contains(w.Body.String(), "not configured") { + t.Fatalf("PUT while not configured: %d %s", w.Code, w.Body.String()) + } + + g := newNotifyFixture(t, extNotifySettings()) + sam := g.registerAndActivate(t, "sam@example.org", "Sam", pw) + got = decode[notifyAccountJSON](t, g.do("GET", "/api/account/notifications", nil, as(sam))) + if !reflect.DeepEqual(got.AvailableEvents, []string{"node.offline", "node.battery", "node.external"}) || + got.ExternalLabel != "Coverage" || !reflect.DeepEqual(got.Events, []string{"node.offline", "node.battery"}) { + t.Fatalf("configured = %+v", got) + } + w = g.do("PUT", "/api/account/notifications", notifyPrefsRequest{Enabled: true, Events: []string{"node.external", "node.offline"}}, as(sam)) + if got := decode[notifyAccountJSON](t, w); w.Code != 200 || !reflect.DeepEqual(got.Events, []string{"node.offline", "node.external"}) { + t.Fatalf("PUT: %d %+v", w.Code, got) + } +} diff --git a/cmd/server/notify_handlers.go b/cmd/server/notify_handlers.go index 4d0b856c5..e0bfee8a8 100644 --- a/cmd/server/notify_handlers.go +++ b/cmd/server/notify_handlers.go @@ -43,6 +43,7 @@ type notifyAccountJSON struct { Enabled bool `json:"enabled"` Events []string `json:"events"` AvailableEvents []string `json:"availableEvents"` + ExternalLabel string `json:"externalLabel,omitempty"` // names node.external when offered Watches []notifyWatchJSON `json:"watches"` Limits notifyLimitsJSON `json:"limits"` } @@ -74,8 +75,13 @@ func notifyPubkey(raw string) (string, bool) { return pk, notifyPubkeyRE.MatchString(pk) } -func availableNotifyEvents(u *users.User) []string { +// availableNotifyEvents lists what u may choose; node.external only when +// the instance configures externalAlerts. +func availableNotifyEvents(u *users.User, external bool) []string { out := append([]string{}, users.NodeNotifyEvents...) + if external { + out = append(out, users.OptionalNodeNotifyEvents...) + } if u.Role == users.RoleAdmin { out = append(out, users.AdminNotifyEvents...) } @@ -112,11 +118,15 @@ func (s *Server) notifyAccount(u *users.User) (notifyAccountJSON, error) { if err != nil { return notifyAccountJSON{}, err } - out := notifyAccountJSON{Enabled: p.Enabled, Events: []string{}, AvailableEvents: availableNotifyEvents(u), + ext := ns.external.url != "" + out := notifyAccountJSON{Enabled: p.Enabled, Events: []string{}, AvailableEvents: availableNotifyEvents(u, ext), Watches: make([]notifyWatchJSON, 0, len(ws)), Limits: notifyLimitsJSON{MaxWatches: ns.maxWatchesPerUser, PerUserPerDay: ns.perUserPerDay, MailsLast24h: perUser[u.ID]}} + if ext { + out.ExternalLabel = ns.external.label + } for _, e := range p.Events { - if u.Role == users.RoleAdmin || !users.IsAdminNotifyEvent(e) { + if (u.Role == users.RoleAdmin || !users.IsAdminNotifyEvent(e)) && (ext || e != users.NotifyNodeExternal) { out.Events = append(out.Events, e) } } @@ -154,6 +164,10 @@ func (s *Server) handleNotifyPut(w http.ResponseWriter, r *http.Request, u *user writeError(w, http.StatusForbidden, "only admins can choose this event") return } + if e == users.NotifyNodeExternal && s.auth.set.notify.external.url == "" { + writeError(w, http.StatusBadRequest, "external alerts are not configured on this instance") + return + } } p, err := s.auth.st.SetNotifyPrefs(u.ID, req.Enabled, req.Events) if err != nil { diff --git a/cmd/server/notify_service.go b/cmd/server/notify_service.go index 4e3d2282c..211de6203 100644 --- a/cmd/server/notify_service.go +++ b/cmd/server/notify_service.go @@ -26,6 +26,9 @@ type notifier struct { // inside the grace loses it. Only the loop goroutine touches them. ingestStale bool ingestResumedAt time.Time + // externalErr is the last tick's reason the externalAlerts feed was not + // used ("" when it was), so each new reason is logged once. + externalErr string } func newNotifier(a *authService, src notifySource, now func() time.Time) *notifier { @@ -168,6 +171,12 @@ func (n *notifier) tick(ctx context.Context) { log.Printf("[notify] read accounts: %v", err) return } + wantExternal := false + if n.a.set.notify.external.url != "" { + for _, p := range prefs { + wantExternal = wantExternal || p.Has(users.NotifyNodeExternal) + } + } wantForeign, wantObservers := false, false for _, p := range prefs { if accounts[p.UserID].Role != users.RoleAdmin { @@ -194,10 +203,14 @@ func (n *notifier) tick(ctx context.Context) { return } } + var external *externalFeed + if wantExternal { + external = n.readExternal(now) + } heard, lock := n.src.lastHeard(pubkeys) res := evaluateNotifications(notifyInput{Now: now, Health: n.src.health(), LowMv: n.src.lowBatteryMv(), Accounts: accounts, Prefs: prefs, Watches: watches, States: states, Nodes: nodes, - Heard: heard, Relayed: n.src.lastRelayed(infra), Observers: observers, IngestStale: stale, IngestResumedAt: n.ingestResumedAt}) + Heard: heard, Relayed: n.src.lastRelayed(infra), Observers: observers, IngestStale: stale, IngestResumedAt: n.ingestResumedAt, External: external}) if err := st.DeleteNotifyStates(res.Drop); err != nil { log.Printf("[notify] delete dropped states, nothing mailed this time: %v", err) return @@ -217,6 +230,33 @@ func (n *notifier) tick(ctx context.Context) { len(accounts), changes, mails, msFloat(time.Since(started)), msFloat(lock)) } +// readExternal fetches and validates the externalAlerts feed. It returns +// nil when the feed cannot be used (fetch failed, malformed, too old), so +// no node.external state changes; a dead feed never mails "resolved". The +// reason is logged when it changes, and once when the feed is usable again. +func (n *notifier) readExternal(now time.Time) *externalFeed { + body, err := n.src.externalFeed() + var f *externalFeed + if err == nil { + f, err = parseExternalFeed(body, now, n.a.set.notify.external.maxAge) + } + why := "" + if err != nil { + why = err.Error() + } + switch { + case why != "" && why != n.externalErr: + log.Printf("[notify] external alerts feed not used, node.external unchanged: %s", why) + case why == "" && n.externalErr != "": + log.Printf("[notify] external alerts feed usable again") + } + n.externalErr = why + if f != nil && f.Skipped > 0 { + log.Printf("[notify] external alerts feed: %d malformed alert(s) skipped", f.Skipped) + } + return f +} + func msFloat(d time.Duration) float64 { return float64(d.Microseconds()) / 1000 } // notifySkipReason says why a user's changes are not mailed; "" means send. @@ -298,7 +338,7 @@ func (a *authService) notifyMail(u users.User, p users.NotifyPrefs, changes []no base := a.set.baseURL.String() lines := make([]mailLine, 0, len(changes)) for _, c := range changes { - lines = append(lines, mailLine{text: notifyChangeText(c), url: notifySubjectURL(base, c)}) + lines = append(lines, mailLine{text: notifyChangeText(c, a.set.notify.external.label), url: notifySubjectURL(base, c)}) } subject := fmt.Sprintf("%d changes on your watched nodes", len(changes)) if len(changes) == 1 { @@ -320,7 +360,8 @@ func (a *authService) notifyMail(u users.User, p users.NotifyPrefs, changes []no } // notifyChangeText is one line of the mail: name, what happened, when (UTC). -func notifyChangeText(c notifyChange) string { +// label names the externalAlerts source. +func notifyChangeText(c notifyChange, label string) string { bad := c.To == users.NotifyBad var what string switch c.Event { @@ -337,6 +378,12 @@ func notifyChangeText(c notifyChange) string { if c.BatteryMv != nil { what += fmt.Sprintf(" (%d mV)", *c.BatteryMv) } + case users.NotifyNodeExternal: + _, key, _ := strings.Cut(c.Subject, "/") + what = label + " resolved (" + key + ")" + if bad { + what = label + ": " + c.Text + } case users.NotifyForeignNew: what = "new foreign node" case users.NotifyObserverOffline: @@ -348,10 +395,18 @@ func notifyChangeText(c notifyChange) string { return c.Name + ": " + what + ", " + c.At.UTC().Format("2006-01-02 15:04 UTC") } -// notifySubjectURL links a change to its node or observer page. +// notifySubjectURL links a change to its node or observer page, or an +// external alert to the link the feed gave it. func notifySubjectURL(base string, c notifyChange) string { - if c.Event == users.NotifyObserverOffline { + switch c.Event { + case users.NotifyObserverOffline: return base + "/#/observers/" + url.PathEscape(c.Subject) + case users.NotifyNodeExternal: + if c.URL != "" { + return c.URL + } + pk, _, _ := strings.Cut(c.Subject, "/") + return base + "/#/nodes/" + url.PathEscape(pk) } return base + "/#/nodes/" + url.PathEscape(c.Subject) } diff --git a/cmd/server/notify_service_test.go b/cmd/server/notify_service_test.go index c9b8b32fc..884876c88 100644 --- a/cmd/server/notify_service_test.go +++ b/cmd/server/notify_service_test.go @@ -28,6 +28,9 @@ type fakeNotifySource struct { heardAsked []string foreignAsked int observersAsked int + feed []byte // externalFeed body; nil with feedErr nil means an empty 200 + feedErr error + feedAsked int } func (f *fakeNotifySource) ready() bool { return f.isReady } @@ -65,6 +68,10 @@ func (f *fakeNotifySource) newestPacket() time.Time { } return f.newestAt() } +func (f *fakeNotifySource) externalFeed() ([]byte, error) { + f.feedAsked++ + return f.feed, f.feedErr +} func (f *fakeNotifySource) observers() ([]notifyObserver, error) { f.observersAsked++ return f.obs, nil @@ -460,7 +467,7 @@ func TestNotifyChangeText(t *testing.T) { {notifyChange{Event: users.NotifyObserverOffline, Name: "O", To: users.NotifyGood, At: at}, "O: observer back online, 2026-10-07 09:05 UTC"}, } for _, c := range cases { - if got := notifyChangeText(c.c); got != c.want { + if got := notifyChangeText(c.c, "Coverage"); got != c.want { t.Errorf("%q; want %q", got, c.want) } } diff --git a/cmd/server/notify_source.go b/cmd/server/notify_source.go index d069318a2..f95f8011c 100644 --- a/cmd/server/notify_source.go +++ b/cmd/server/notify_source.go @@ -2,6 +2,7 @@ package main import ( "database/sql" + "net/http" "strings" "time" ) @@ -16,7 +17,8 @@ type notifySource interface { lastHeard(pubkeys []string) (map[string]time.Time, time.Duration) // and how long the store lock was held lastRelayed(pubkeys []string) map[string]time.Time observers() ([]notifyObserver, error) - newestPacket() time.Time // zero when the store holds no packet + newestPacket() time.Time // zero when the store holds no packet + externalFeed() ([]byte, error) // the externalAlerts feed body (#2177); only called when configured } type serverNotifySource struct{ s *Server } @@ -67,6 +69,12 @@ func (src serverNotifySource) newestPacket() time.Time { return src.s.store.NewestFirstSeen() } +var externalFeedClient = &http.Client{Timeout: externalFeedTimeout} + +func (src serverNotifySource) externalFeed() ([]byte, error) { + return fetchExternalFeed(externalFeedClient, src.s.auth.set.notify.external.url) +} + func (src serverNotifySource) observers() ([]notifyObserver, error) { list, err := src.s.db.GetObservers() if err != nil { diff --git a/cmd/server/openapi.go b/cmd/server/openapi.go index 0292bff41..2410b3e24 100644 --- a/cmd/server/openapi.go +++ b/cmd/server/openapi.go @@ -41,12 +41,15 @@ type paramMeta struct { func routeDescriptions() map[string]routeMeta { return map[string]routeMeta{ // Config - "GET /api/config/cache": {Summary: "Get cache configuration", Tag: "config"}, - "GET /api/config/client": {Summary: "Get client configuration", Tag: "config"}, - "GET /api/config/regions": {Summary: "Get configured regions", Tag: "config"}, - "GET /api/config/theme": {Summary: "Get theme configuration", Description: "Returns color maps, CSS variables, and theme defaults.", Tag: "config"}, - "GET /api/config/map": {Summary: "Get map configuration", Tag: "config"}, - "GET /api/config/geo-filter": {Summary: "Get geo-filter configuration", Tag: "config"}, + "GET /api/config/cache": {Summary: "Get cache configuration", Tag: "config"}, + "GET /api/config/client": {Summary: "Get client configuration", Tag: "config"}, + "GET /api/config/areas/geojson": {Summary: "Area shapes as GeoJSON", Description: "Every area (config.json and areasFile) as a GeoJSON FeatureCollection of MultiPolygons with code, label and layer, simplified to about 450 m for drawing.", Tag: "config", + QueryParams: []paramMeta{{Name: "layer", Description: "Only this layer's areas; omitted means every layer", Type: "string"}}}, + "GET /api/config/regions": {Summary: "Get configured regions", Tag: "config"}, + "GET /api/config/region-quick-picks": {Summary: "Get region quick picks", Description: "Named groups of region (IATA) codes from config regionQuickPicks, offered as one-tap choices by the region filter. Always a list; empty when none are configured.", Tag: "config"}, + "GET /api/config/theme": {Summary: "Get theme configuration", Description: "Returns color maps, CSS variables, and theme defaults.", Tag: "config"}, + "GET /api/config/map": {Summary: "Get map configuration", Tag: "config"}, + "GET /api/config/geo-filter": {Summary: "Get geo-filter configuration", Tag: "config"}, // Admin / system "GET /api/health": {Summary: "Health check", Description: "Returns server health, uptime, and memory stats.", Tag: "admin"}, @@ -103,8 +106,8 @@ func routeDescriptions() map[string]routeMeta { "POST /api/mail/brevo/webhook": {Summary: "Brevo delivery-event webhook", Description: "Authenticated with Authorization: Bearer . Registered only when the secret is set.", Tag: "users"}, // Node notifications (user management, part E) - "GET /api/account/notifications": {Summary: "Get own notification settings", Description: "Returns {enabled, events, availableEvents, watches: [{pubkey, name, known, createdAt}], limits: {maxWatches, perUserPerDay, mailsLast24h}}. Creates the default settings (on, node.offline and node.battery) on first use. known is false once the node left the analyzer database. Registered only when userManagement.notifications.enabled.", Tag: "users", Session: true}, - "PUT /api/account/notifications": {Summary: "Change own notification settings", Description: "Body {enabled, events}. events from node.offline, node.battery and, for admins, foreign.new and observer.offline. Answers the GET body. 400 unknown event type, 403 an admin event chosen by a non-admin. Events left out lose their stored state, so choosing them again starts without a mail.", Tag: "users", Session: true}, + "GET /api/account/notifications": {Summary: "Get own notification settings", Description: "Returns {enabled, events, availableEvents, externalLabel, watches: [{pubkey, name, known, createdAt}], limits: {maxWatches, perUserPerDay, mailsLast24h}}. node.external and externalLabel appear only when notifications.externalAlerts is configured. Creates the default settings (on, node.offline and node.battery) on first use. known is false once the node left the analyzer database. Registered only when userManagement.notifications.enabled.", Tag: "users", Session: true}, + "PUT /api/account/notifications": {Summary: "Change own notification settings", Description: "Body {enabled, events}. events from node.offline, node.battery, node.external (when externalAlerts is configured) and, for admins, foreign.new and observer.offline. Answers the GET body. 400 unknown event type or node.external without externalAlerts, 403 an admin event chosen by a non-admin. Events left out lose their stored state, so choosing them again starts without a mail.", Tag: "users", Session: true}, "PUT /api/account/notifications/watches/{pubkey}": {Summary: "Watch a node", Description: "Answers the GET body. 400 when pubkey is not 64 hex characters, 404 when the node is not in the analyzer database, 409 when userManagement.notifications.maxWatchesPerUser nodes are watched. Watching a watched node is 200.", Tag: "users", Session: true}, "DELETE /api/account/notifications/watches/{pubkey}": {Summary: "Stop watching a node", Description: "Answers the GET body; removing a node that is not watched is 200. 400 when pubkey is not 64 hex characters.", Tag: "users", Session: true}, "POST /api/account/notifications/watch-my-nodes": {Summary: "Watch the synced My nodes", Description: "Copies the pubkeys of the caller's synced meshcore-my-nodes setting into the watch list, up to the limit. Answers {added, already, skipped, account}; skipped counts malformed keys, nodes not in the analyzer database and nodes over the limit; account is the GET body.", Tag: "users", Session: true}, @@ -171,6 +174,29 @@ func routeDescriptions() map[string]routeMeta { {Name: "window", Description: "Time window: 1h, 24h, or 7d (default 24h)", Type: "string"}, }}, + // Data tab (#data): every packet of the last data.days days, placed by area + "GET /api/data/config": {Summary: "Data tab configuration", Description: "Whether the Data tab is on, and if so its layer, areas in order, home area, the periods the index reaches, packet kinds, type names, filter dimensions, rows held and how far back it is filled.", Tag: "data"}, + "GET /api/data/summary": {Summary: "Data tab summary", Description: "One period's packets, those heard outside the area they started in, how starts were decided, the start-by-receiving-area matrix overall and per packet kind, and the flows between areas with the relays that carried them. Cached 60 s. 404 when the tab is off.", Tag: "data", + QueryParams: []paramMeta{{Name: "window", Description: "24h, 7d or 30d, as far as data.days reaches", Type: "string", Required: true}}}, + "GET /api/data/cube": {Summary: "Data tab cube", Description: "Packets per time bucket along origin, heard, type, scope, how, route, through and channel: rows of [bucket, origin, heard, type, scope, how, route, through, channel, packets], each an index into the lists beside it. Cached 60 s. 404 when the tab is off.", Tag: "data", + QueryParams: []paramMeta{{Name: "window", Description: "24h, 7d or 30d, as far as data.days reaches", Type: "string", Required: true}}}, + "GET /api/data/path": {Summary: "Path watch between two repeaters", Description: "Packets that passed the first repeater and those that then reached the second, per 24 hours (the last 24 hours last), the share that got through against the range it usually falls in, hops and routes between the two, and route changes in words (a repeater that dropped out and went quiet or was rerouted around, one that started carrying, the main route moving). Read from the packet store's path index; cached 5 minutes per pair. 404 when the Data tab is off.", Tag: "data", + QueryParams: []paramMeta{ + {Name: "from", Description: "Public key of the first repeater", Type: "string", Required: true}, + {Name: "to", Description: "Public key of the second repeater", Type: "string", Required: true}, + {Name: "window", Description: "7d (default) or 30d of days shown; 24h shows a week", Type: "string"}, + {Name: "basis", Description: "all (default) or adverts, which counts only adverts and is steadier", Type: "string"}, + }}, + "POST /api/data/paths": {Summary: "Path watches, several at once", Description: "The same as GET /api/data/path for up to 24 pairs, in order: body {window, basis, pairs: [{from, to}]}. For a watch list panel. 404 when the Data tab is off.", Tag: "data"}, + "GET /api/data/dashboards": {Summary: "Data tab dashboards", Description: "The built-in dashboards followed by the operator's (data.dashboardsFile), validated, with the one to open first and the home area. Each is a schema-1 document of panels: a query over the cube, a panel type and a place on a 12-column grid. 404 when the tab is off.", Tag: "data"}, + "GET /api/data/packets": {Summary: "Packets behind a Data tab figure", Description: "The packet rows (one per receiving area) passing every filter, newest first, at most 2,000 with the full total. Two run at a time. 404 when the tab is off.", Tag: "data", + QueryParams: []paramMeta{ + {Name: "window", Description: "24h, 7d or 30d", Type: "string", Required: true}, + {Name: "from", Description: "Unix seconds, inclusive", Type: "integer"}, + {Name: "to", Description: "Unix seconds, exclusive", Type: "integer"}, + {Name: "f", Description: `JSON list of filters, each {"d": dimension, "v": [values], "n": 1 to exclude, "x": 1 for an exact "through" match}. Dimensions: border, origin, heard, through, kind, type, channel, scope, sclass, how, routing.`, Type: "string"}, + }}, + // Analytics "GET /api/analytics/rf": {Summary: "RF analytics", Description: "SNR/RSSI distributions and statistics.", Tag: "analytics"}, "GET /api/analytics/topology": {Summary: "Network topology", Description: "Hop-count distribution and route analysis.", Tag: "analytics"}, @@ -487,12 +513,13 @@ func buildOpenAPISpec(router *mux.Router, version string) map[string]interface{} } // Build tags array (sorted) - tagOrder := []string{"admin", "analytics", "channels", "config", "nodes", "observers", "packets", "users"} + tagOrder := []string{"admin", "analytics", "channels", "config", "data", "nodes", "observers", "packets", "users"} tagDescriptions := map[string]string{ "admin": "Server administration and diagnostics", "analytics": "Network analytics and statistics", "channels": "Mesh channel operations", "config": "Server configuration", + "data": "The Data tab: packets placed by the area they started in and the areas that heard them", "nodes": "Mesh node operations", "observers": "Packet observer/gateway operations", "packets": "Packet capture and decoding", diff --git a/cmd/server/pathhop_eviction_1908_test.go b/cmd/server/pathhop_eviction_1908_test.go index 33b6d3c79..dd89031ac 100644 --- a/cmd/server/pathhop_eviction_1908_test.go +++ b/cmd/server/pathhop_eviction_1908_test.go @@ -152,7 +152,7 @@ func BenchmarkPathHopEviction1908(b *testing.B) { store := &PacketStore{ packets: make([]*StoreTx, count), byPathHop: make(map[string][]*StoreTx, len(pubkeys)+256), - spIndex: make(map[string]int), + spTxIndex: make(map[string][]*StoreTx), retentionHours: 1, } hopsSeen := make(map[string]bool, hops*2) diff --git a/cmd/server/region_nodes_test.go b/cmd/server/region_nodes_test.go index f8f4a5800..9ee63bb78 100644 --- a/cmd/server/region_nodes_test.go +++ b/cmd/server/region_nodes_test.go @@ -186,6 +186,7 @@ func TestHandleNodesRegionUsesStore(t *testing.T) { srv.store.regionNodesMu.Lock() srv.store.regionNodesCache = map[string]regionNodesEntry{} srv.store.regionNodesMu.Unlock() + srv.invalidateNodesCache() // the 15 s /api/nodes response cache, likewise if got := get(); fmt.Sprint(got) != "[aabbccdd11223344 eeff00112233aabb]" { t.Errorf("region SJC must come from the store: got %v", got) } diff --git a/cmd/server/region_quick_picks_test.go b/cmd/server/region_quick_picks_test.go new file mode 100644 index 000000000..1676f5843 --- /dev/null +++ b/cmd/server/region_quick_picks_test.go @@ -0,0 +1,88 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "github.com/gorilla/mux" +) + +// Region quick picks: named groups of region (IATA) codes offered as one-tap +// choices in the region filter, configured in config.json. One deployment +// injected these with an nginx sub_filter and a script that wrapped +// RegionFilter; this makes them a configured feature. + +func TestNormalizedRegionQuickPicks_CleansConfig(t *testing.T) { + var cfg Config + raw := `{"regionQuickPicks": [ + {"name": " California ", "description": "California observers", "regions": ["sfo", " SJC", "SFO", "", "lax"]}, + {"name": "", "regions": ["BRU"]}, + {"name": "Empty", "regions": []}, + {"name": "Monterey", "regions": ["mry"]} + ]}` + if err := json.Unmarshal([]byte(raw), &cfg); err != nil { + t.Fatal(err) + } + got := cfg.NormalizedRegionQuickPicks() + want := []RegionQuickPick{ + {Name: "California", Description: "California observers", Regions: []string{"SFO", "SJC", "LAX"}}, + {Name: "Monterey", Regions: []string{"MRY"}}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %+v\nwant %+v", got, want) + } +} + +func TestNormalizedRegionQuickPicks_CapsCounts(t *testing.T) { + var cfg Config + for i := 0; i < maxRegionQuickPicks+5; i++ { + codes := make([]string, maxRegionQuickPickRegions+10) + for j := range codes { + codes[j] = fmt.Sprintf("C%03d", j) + } + cfg.RegionQuickPicks = append(cfg.RegionQuickPicks, RegionQuickPick{Name: fmt.Sprintf("Pick %d", i), Regions: codes}) + } + got := cfg.NormalizedRegionQuickPicks() + if len(got) != maxRegionQuickPicks { + t.Fatalf("got %d picks, want the cap of %d", len(got), maxRegionQuickPicks) + } + if len(got[0].Regions) != maxRegionQuickPickRegions { + t.Fatalf("got %d regions in a pick, want the cap of %d", len(got[0].Regions), maxRegionQuickPickRegions) + } +} + +func TestNormalizedRegionQuickPicks_NilConfigIsEmpty(t *testing.T) { + if got := (*Config)(nil).NormalizedRegionQuickPicks(); got == nil || len(got) != 0 { + t.Fatalf("got %#v, want an empty non-nil slice", got) + } +} + +func TestHandleConfigRegionQuickPicks(t *testing.T) { + db := setupTestDB(t) + defer db.Close() + cfg := &Config{Port: 3000, RegionQuickPicks: []RegionQuickPick{{Name: "California", Regions: []string{"sfo", "sjc"}}}} + srv := NewServer(db, cfg, NewHub()) + router := mux.NewRouter() + srv.RegisterRoutes(router) + + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest("GET", "/api/config/region-quick-picks", nil)) + if w.Code != 200 { + t.Fatalf("status %d", w.Code) + } + body := strings.TrimSpace(w.Body.String()) + if body != `{"quickPicks":[{"name":"California","regions":["SFO","SJC"]}]}` { + t.Fatalf("body = %s", body) + } + + srv.cfg = &Config{Port: 3000} + w = httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest("GET", "/api/config/region-quick-picks", nil)) + if got := strings.TrimSpace(w.Body.String()); got != `{"quickPicks":[]}` { + t.Fatalf("without quick picks, body = %s, want an empty list", got) + } +} diff --git a/cmd/server/relay_airtime_share_test.go b/cmd/server/relay_airtime_share_test.go index 988b906ff..15c1ca286 100644 --- a/cmd/server/relay_airtime_share_test.go +++ b/cmd/server/relay_airtime_share_test.go @@ -28,7 +28,6 @@ func newRelayAirtimeShareTestStore(packets []*StoreTx) *PacketStore { chanCache: make(map[string]*cachedResult), distCache: make(map[string]*cachedResult), subpathCache: make(map[string]*cachedResult), - spIndex: make(map[string]int), spTxIndex: make(map[string][]*StoreTx), advertPubkeys: make(map[string]int), } diff --git a/cmd/server/repeater_snapshot_1908_test.go b/cmd/server/repeater_snapshot_1908_test.go index 4c1ec78ec..b4e41d2a1 100644 --- a/cmd/server/repeater_snapshot_1908_test.go +++ b/cmd/server/repeater_snapshot_1908_test.go @@ -18,7 +18,7 @@ func relaySnapshotStore1908(count, nodes, expired int) *PacketStore { store := &PacketStore{ packets: make([]*StoreTx, count), byPathHop: make(map[string][]*StoreTx, nodes+256), - spIndex: make(map[string]int), + spTxIndex: make(map[string][]*StoreTx), retentionHours: 1, } pt := 5 diff --git a/cmd/server/resolved_index_test.go b/cmd/server/resolved_index_test.go index 90c2bfb89..f03c9993f 100644 --- a/cmd/server/resolved_index_test.go +++ b/cmd/server/resolved_index_test.go @@ -288,7 +288,7 @@ func TestEviction_ByNodeCleanup_OnDemandSQL(t *testing.T) { byNode: make(map[string][]*StoreTx), nodeHashes: make(map[string]map[string]bool), byPayloadType: make(map[int][]*StoreTx), - spIndex: make(map[string]int), + spTxIndex: make(map[string][]*StoreTx), distHops: make([]distHopRecord, 0), distPaths: make([]distPathRecord, 0), rfCache: make(map[string]*cachedResult), @@ -363,7 +363,7 @@ func TestRunEviction_NoLockDuringSQLFetch(t *testing.T) { nodeHashes: make(map[string]map[string]bool), byPayloadType: make(map[int][]*StoreTx), byPathHop: make(map[string][]*StoreTx), - spIndex: make(map[string]int), + spTxIndex: make(map[string][]*StoreTx), distHops: make([]distHopRecord, 0), distPaths: make([]distPathRecord, 0), rfCache: make(map[string]*cachedResult), @@ -1152,7 +1152,6 @@ func TestResolvedPubkeyIndex_BoundedByEviction(t *testing.T) { nodeHashes: make(map[string]map[string]bool), byPayloadType: make(map[int][]*StoreTx), byPathHop: make(map[string][]*StoreTx), - spIndex: make(map[string]int), spTxIndex: make(map[string][]*StoreTx), distHops: make([]distHopRecord, 0), distPaths: make([]distPathRecord, 0), @@ -1278,7 +1277,6 @@ func TestRunEviction_TriggersCompaction(t *testing.T) { nodeHashes: make(map[string]map[string]bool), byPayloadType: make(map[int][]*StoreTx), byPathHop: make(map[string][]*StoreTx), - spIndex: make(map[string]int), spTxIndex: make(map[string][]*StoreTx), distHops: make([]distHopRecord, 0), distPaths: make([]distPathRecord, 0), @@ -1366,7 +1364,6 @@ func TestResolvedPubkeyIndex_MemoryStableThroughEvictionCycles(t *testing.T) { nodeHashes: make(map[string]map[string]bool), byPayloadType: make(map[int][]*StoreTx), byPathHop: make(map[string][]*StoreTx), - spIndex: make(map[string]int), spTxIndex: make(map[string][]*StoreTx), distHops: make([]distHopRecord, 0), distPaths: make([]distPathRecord, 0), diff --git a/cmd/server/routes.go b/cmd/server/routes.go index 5f367d1b7..676f69020 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/meshcore-analyzer/areamap" "log" "math" "net/http" @@ -33,6 +34,8 @@ type Server struct { cfg *Config hub *Hub store *PacketStore // in-memory packet store (nil = fallback to DB) + data *dataService // the Data tab's index (nil = tab off) + paths *pathIndex // path watch history (nil = Data tab off) configDir string // directory containing config.json (for write-back via PUT /api/config/geo-filter) startedAt time.Time perfStats *PerfStats @@ -68,6 +71,17 @@ type Server struct { // queries against a 4-connection pool. statsSF singleflight.Group + // /api/nodes responses, encoded, keyed by the canonical query string and + // kept for nodesResponseTTL. Identical queries in that window share one + // build (nodesSF collapses concurrent misses). setGeoFilter drops them. + nodesCacheMu sync.Mutex + nodesCache map[string]nodesCacheEntry + nodesCacheBytes int // sum of len(body) over nodesCache; bounded by nodesCacheMaxBytes + nodesSF singleflight.Group + // Test-only hook fired each time handleNodes builds a response (not when + // one is served from cache). Nil in production. See nodes_response_cache_test.go. + nodesComputeHook func() + // Guards s.cfg.GeoFilter — read by ingest/handler goroutines, written by PUT handler cfgMu sync.RWMutex @@ -90,6 +104,10 @@ type Server struct { scopeAuditCache map[string]*ScopeAuditResponse scopeAuditCachedAt map[string]time.Time scopeAuditSF singleflight.Group + // #2142: the transport view (?mode=transport), cached per window with the + // same TTLs; computed under scopeAuditSF with a "transport|" key. + scopeTransportCache map[string]*ScopeTransportResponse + scopeTransportCachedAt map[string]time.Time // #1975: /api/scope-audit window cache and its single-flight guard, so a // burst of viewers on a cold cache recomputes the network-wide scan once @@ -218,8 +236,10 @@ func (s *Server) getGeoFilter() *GeoFilterConfig { // setGeoFilter atomically swaps the geo_filter config; used by PUT /api/config/geo-filter. func (s *Server) setGeoFilter(gf *GeoFilterConfig) { s.cfgMu.Lock() - defer s.cfgMu.Unlock() s.cfg.GeoFilter = gf + s.cfgMu.Unlock() + // Cached /api/nodes pages were filtered with the old polygon. + s.invalidateNodesCache() } // RegisterRoutes sets up all HTTP routes on the given router. @@ -256,11 +276,20 @@ func (s *Server) RegisterRoutes(r *mux.Router) { r.HandleFunc("/api/config/cache", s.handleConfigCache).Methods("GET") r.HandleFunc("/api/config/client", s.handleConfigClient).Methods("GET") r.HandleFunc("/api/config/regions", s.handleConfigRegions).Methods("GET") + r.HandleFunc("/api/config/region-quick-picks", s.handleConfigRegionQuickPicks).Methods("GET") r.HandleFunc("/api/config/theme", s.handleConfigTheme).Methods("GET") r.HandleFunc("/api/config/map", s.handleConfigMap).Methods("GET") r.HandleFunc("/api/config/geo-filter", s.handleConfigGeoFilter).Methods("GET") r.HandleFunc("/api/config/areas", s.handleConfigAreas).Methods("GET") r.HandleFunc("/api/config/areas/polygons", s.handleConfigAreasPolygons).Methods("GET") + r.HandleFunc("/api/config/areas/geojson", s.handleConfigAreasGeoJSON).Methods("GET") + r.HandleFunc("/api/data/config", s.handleDataConfig).Methods("GET") + r.HandleFunc("/api/data/summary", s.handleDataSummary).Methods("GET") + r.HandleFunc("/api/data/cube", s.handleDataCube).Methods("GET") + r.HandleFunc("/api/data/packets", s.handleDataPackets).Methods("GET") + r.HandleFunc("/api/data/dashboards", s.handleDataDashboards).Methods("GET") + r.HandleFunc("/api/data/path", s.handleDataPath).Methods("GET") + r.HandleFunc("/api/data/paths", s.handleDataPaths).Methods("POST") r.Handle("/api/config/geo-filter", s.requireAdmin(http.HandlerFunc(s.handlePutConfigGeoFilter))).Methods("PUT") // Readiness endpoint (gated on background init completion) @@ -542,13 +571,22 @@ func (s *Server) handleConfigAreas(w http.ResponseWriter, r *http.Request) { type areaListEntry struct { Key string `json:"key"` Label string `json:"label"` + Layer string `json:"layer"` } result := make([]areaListEntry, 0, len(s.cfg.Areas)) for k, v := range s.cfg.Areas { if v.Label == "" { continue // skip comment/invalid entries (e.g. "_comment" keys in config) } - result = append(result, areaListEntry{Key: k, Label: v.Label}) + result = append(result, areaListEntry{Key: k, Label: v.Label, Layer: areamap.DefaultLayer}) + } + // Areas from areasFile, in the file's order, with their layer. + if s.cfg.areaMap != nil { + for _, a := range s.cfg.areaMap.Areas("") { + if s.cfg.fileArea(a.Code) { + result = append(result, areaListEntry{Key: a.Code, Label: a.Label, Layer: a.Layer}) + } + } } writeJSON(w, result) } @@ -592,6 +630,15 @@ func (s *Server) handleConfigRegions(w http.ResponseWriter, r *http.Request) { writeJSON(w, regions) } +// RegionQuickPicksResponse is GET /api/config/region-quick-picks. +type RegionQuickPicksResponse struct { + QuickPicks []RegionQuickPick `json:"quickPicks"` +} + +func (s *Server) handleConfigRegionQuickPicks(w http.ResponseWriter, r *http.Request) { + writeJSON(w, RegionQuickPicksResponse{QuickPicks: s.cfg.NormalizedRegionQuickPicks()}) +} + func (s *Server) handleConfigTheme(w http.ResponseWriter, r *http.Request) { theme := LoadTheme(".") @@ -1143,6 +1190,9 @@ func (s *Server) handlePackets(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("order") == "asc" { q.Order = "ASC" } + if q.Area != "" { + q.startedIn = s.data.startedIn(q.Area) + } if v := r.URL.Query().Get("type"); v != "" { t, _ := strconv.Atoi(v) q.Type = &t @@ -1166,7 +1216,7 @@ func (s *Server) handlePackets(w http.ResponseWriter, r *http.Request) { } result.Limit = q.Limit result.Offset = q.Offset - writeJSON(w, result) + writeJSON(w, s.data.withOrigins(result)) return } @@ -1184,7 +1234,7 @@ func (s *Server) handlePackets(w http.ResponseWriter, r *http.Request) { result.Limit = q.Limit result.Offset = q.Offset - writeJSON(w, result) + writeJSON(w, s.data.withOrigins(result)) } func (s *Server) handlePacketTimestamps(w http.ResponseWriter, r *http.Request) { @@ -1378,6 +1428,7 @@ func (s *Server) handlePacketDetail(w http.ResponseWriter, r *http.Request) { Path: pathHops, ObservationCount: observationCount, Observations: mapSliceToObservations(observations), + Origin: s.data.originOf(hash), }) } @@ -1420,7 +1471,100 @@ func (s *Server) handleDecode(w http.ResponseWriter, r *http.Request) { // --- Node Handlers --- +// nodesResponseTTL is how long an /api/nodes response is reused for an +// identical query. Relay and usefulness data under it is already cached for +// 15 s (#1257), and the client keeps its own node list for 90 s. +const nodesResponseTTL = 15 * time.Second + +// nodesCacheMaxBytes bounds the encoded /api/nodes responses held at once. A +// full-list response is a few MB, so an entry count alone would not bound the +// heap if many distinct queries arrived inside one TTL. +const nodesCacheMaxBytes = 32 << 20 + +type nodesCacheEntry struct { + body []byte + exp time.Time +} + func (s *Server) handleNodes(w http.ResponseWriter, r *http.Request) { + // Encode() sorts by key, so parameter order does not split the cache. The + // blacklist and hidden-prefix generations are part of the key so a change + // to either misses the cache at once (same pattern as #1629). + key := fmt.Sprintf("%d|%d|%s", s.cfg.BlacklistGeneration(), s.cfg.HiddenNamePrefixesGeneration(), r.URL.Query().Encode()) + if body, ok := s.cachedNodesResponse(key); ok { + writeJSONBytes(w, body) + return + } + v, err, _ := s.nodesSF.Do(key, func() (interface{}, error) { + if body, ok := s.cachedNodesResponse(key); ok { + return body, nil + } + if s.nodesComputeHook != nil { + s.nodesComputeHook() + } + resp, err := s.buildNodesResponse(r) + if err != nil { + return nil, err + } + body, err := json.Marshal(resp) + if err != nil { + return nil, err + } + body = append(body, '\n') // byte-identical to json.Encoder output + s.storeNodesResponse(key, body) + return body, nil + }) + if err != nil { + writeError(w, 500, err.Error()) + return + } + writeJSONBytes(w, v.([]byte)) +} + +func (s *Server) cachedNodesResponse(key string) ([]byte, bool) { + s.nodesCacheMu.Lock() + defer s.nodesCacheMu.Unlock() + e, ok := s.nodesCache[key] + if !ok || time.Now().After(e.exp) { + return nil, false + } + return e.body, true +} + +func (s *Server) storeNodesResponse(key string, body []byte) { + if len(body) > nodesCacheMaxBytes/4 { + return // one oversized response must not evict everything else + } + s.nodesCacheMu.Lock() + defer s.nodesCacheMu.Unlock() + now := time.Now() + for k, e := range s.nodesCache { // drop expired entries first + if now.After(e.exp) { + s.nodesCacheBytes -= len(e.body) + delete(s.nodesCache, k) + } + } + if old, ok := s.nodesCache[key]; ok { + s.nodesCacheBytes -= len(old.body) + } + if s.nodesCache == nil || len(s.nodesCache) >= maxCacheEntries || s.nodesCacheBytes+len(body) > nodesCacheMaxBytes { + s.nodesCache = make(map[string]nodesCacheEntry) + s.nodesCacheBytes = 0 + } + s.nodesCache[key] = nodesCacheEntry{body: body, exp: now.Add(nodesResponseTTL)} + s.nodesCacheBytes += len(body) +} + +// invalidateNodesCache drops every cached /api/nodes response. +func (s *Server) invalidateNodesCache() { + s.nodesCacheMu.Lock() + s.nodesCache = nil + s.nodesCacheBytes = 0 + s.nodesCacheMu.Unlock() +} + +// buildNodesResponse builds one /api/nodes page from the request's query. +func (s *Server) buildNodesResponse(r *http.Request) (NodeListResponse, error) { q := r.URL.Query() limit := queryLimit(r, 50, s.cfg.ListLimits.NodesMax) offset := queryInt(r, "offset", 0) @@ -1438,8 +1582,7 @@ func (s *Server) handleNodes(w http.ResponseWriter, r *http.Request) { } nodes, total, counts, err := s.db.GetNodes(nq) if err != nil { - writeError(w, 500, err.Error()) - return + return NodeListResponse{}, err } // Whether more rows exist is decided HERE, against the raw SQL page and the // real COUNT(*), because both other candidate signals are destroyed further @@ -1595,8 +1738,13 @@ func (s *Server) handleNodes(w http.ResponseWriter, r *http.Request) { var areaNodes map[string]bool if s.store != nil { areaNodes = s.store.resolveAreaNodes(area) - } else if s.cfg != nil && s.cfg.Areas != nil { - if entry, ok := s.cfg.Areas[area]; ok { + } else if s.cfg != nil { + entry, ok := s.cfg.Areas[area] + if !ok && s.cfg.fileArea(area) { + m := s.cfg.areaMap + entry, ok = AreaEntry{match: func(lat, lon float64) bool { return m.Contains(area, lat, lon) }}, true + } + if ok { pks, err := s.db.GetNodePubkeysInArea(entry) if err == nil { areaNodes = make(map[string]bool, len(pks)) @@ -1618,7 +1766,7 @@ func (s *Server) handleNodes(w http.ResponseWriter, r *http.Request) { total = len(filtered) } } - writeJSON(w, NodeListResponse{Nodes: nodes, Total: total, Counts: counts, HasMore: hasMore}) + return NodeListResponse{Nodes: nodes, Total: total, Counts: counts, HasMore: hasMore}, nil } func (s *Server) handleNodeSearch(w http.ResponseWriter, r *http.Request) { @@ -3186,6 +3334,15 @@ func writeJSONStatus(w http.ResponseWriter, code int, v interface{}) { } } +// writeJSONBytes writes an already-encoded JSON body with status 200. +func writeJSONBytes(w http.ResponseWriter, body []byte) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + if _, err := w.Write(body); err != nil { + log.Printf("[routes] JSON write error: %v", err) + } +} + func writeError(w http.ResponseWriter, code int, msg string) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) diff --git a/cmd/server/scope_audit.go b/cmd/server/scope_audit.go index f4694d5e7..69ff952c6 100644 --- a/cmd/server/scope_audit.go +++ b/cmd/server/scope_audit.go @@ -849,6 +849,50 @@ type ScopeAuditResponse struct { Repeaters []ScopeAuditRow `json:"repeaters"` } +// ScopeTransportRow is one repeater seen forwarding in the window, in the +// transport view of the scope audit (#2142, ?mode=transport). Unlike +// ScopeAuditRow it does not require a declared-regions answer: "transported" +// means seen carrying, not configured for, and the declared side is reported +// where it exists (asked) and left null where it does not. +type ScopeTransportRow struct { + PublicKey string `json:"publicKey"` + Name *string `json:"name"` // null = no nodes row held for this key + Role *string `json:"role"` + + // Transported lists the named region scopes this repeater was seen + // forwarding in the window, most packets first. + Transported []ScopeObservation `json:"transported"` + UnscopedPackets int64 `json:"unscopedPackets"` // plain floods forwarded + UnmatchedPackets int64 `json:"unmatchedPackets"` // scoped, but no region key held here + AmbiguousHops int64 `json:"ambiguousHops"` // hops shared with another repeater's prefix, credited to neither + + // Asked is whether a declared-regions answer exists for this repeater. + // DeclaredRegions is null when it does not, [] when it answered with no + // named region. NotObserved (declared, not seen carried) is null when not + // asked. + Asked bool `json:"asked"` + DeclaredRegions []string `json:"declaredRegions"` + DeclaredWildcard bool `json:"declaredWildcard"` + ConfigState string `json:"configState,omitempty"` + DeclaredAt string `json:"declaredAt,omitempty"` + NotObserved []string `json:"notObserved"` + + // CarriesScope is set only when the request named a scope (?scope=): + // whether this repeater was seen carrying it in the window. + CarriesScope *bool `json:"carriesScope,omitempty"` +} + +// ScopeTransportResponse is GET /api/scope-audit?mode=transport. +type ScopeTransportResponse struct { + Mode string `json:"mode"` // "transport" + Window string `json:"window"` + Since string `json:"since"` + Scope string `json:"scope,omitempty"` // normalised ?scope= filter, when given + Carrying *int `json:"carrying,omitempty"` + NotCarry *int `json:"notCarrying,omitempty"` + Repeaters []ScopeTransportRow `json:"repeaters"` +} + // NodeScopesResponse is the payload for GET /api/nodes/{pubkey}/scopes: the // observed-forwarding side (ScopeConformance, embedded BY VALUE so its three // scope states sit at the JSON top level — unmatched and unscoped are @@ -998,6 +1042,16 @@ func (s *Server) handleScopeAudit(w http.ResponseWriter, r *http.Request) { sinceISO := time.Now().Add(-lookback).UTC().Format(time.RFC3339) + switch r.URL.Query().Get("mode") { + case "", "declared": + case "transport": + s.serveScopeTransport(w, r, window, sinceISO) + return + default: + writeError(w, 400, "mode must be declared or transport") + return + } + if cached, ok := s.scopeAuditCached(window); ok { writeJSON(w, cached) return @@ -1259,3 +1313,237 @@ func (s *Server) computeScopeAudit(window, sinceISO string) (*ScopeAuditResponse return resp, nil } + +// serveScopeTransport answers GET /api/scope-audit?mode=transport (#2142): +// the cached per-window transport view, with the optional region filter +// applied to a copy so the cached response is never changed. +func (s *Server) serveScopeTransport(w http.ResponseWriter, r *http.Request, window, sinceISO string) { + resp, ok := s.scopeTransportCached(window) + if !ok { + v, err, _ := s.scopeAuditSF.Do("transport|"+window, func() (interface{}, error) { + if cached, ok := s.scopeTransportCached(window); ok { + return cached, nil + } + fresh, cErr := s.computeScopeTransport(window, sinceISO) + if cErr != nil { + return nil, cErr + } + s.scopeTransportStore(window, fresh) + return fresh, nil + }) + if err != nil { + writeError(w, 500, err.Error()) + return + } + resp = v.(*ScopeTransportResponse) + } + // ?scope= names a region SCOPE (be, be-van). ?region= is kept for the + // observer IATA filter, as on every other endpoint. + if scope := strings.ToLower(normScope(strings.TrimSpace(r.URL.Query().Get("scope")))); scope != "" { + resp = withTransportScope(resp, scope) + } + writeJSON(w, resp) +} + +func (s *Server) scopeTransportCached(window string) (*ScopeTransportResponse, bool) { + s.scopeAuditMu.Lock() + defer s.scopeAuditMu.Unlock() + cached, ok := s.scopeTransportCache[window] + if !ok || time.Since(s.scopeTransportCachedAt[window]) >= scopeAuditTTLFor(window) { + return nil, false + } + return cached, true +} + +func (s *Server) scopeTransportStore(window string, resp *ScopeTransportResponse) { + s.scopeAuditMu.Lock() + defer s.scopeAuditMu.Unlock() + if s.scopeTransportCache == nil { + s.scopeTransportCache = make(map[string]*ScopeTransportResponse) + s.scopeTransportCachedAt = make(map[string]time.Time) + } + s.scopeTransportCache[window] = resp + s.scopeTransportCachedAt[window] = time.Now() +} + +// withTransportScope returns a copy of resp in which every row says whether +// it was seen carrying scope, with the two counts. scope is already +// normalised (no '#', lower case). +func withTransportScope(resp *ScopeTransportResponse, scope string) *ScopeTransportResponse { + out := *resp + out.Scope = scope + out.Repeaters = make([]ScopeTransportRow, len(resp.Repeaters)) + carrying, notCarrying := 0, 0 + for i, row := range resp.Repeaters { + carries := false + for _, so := range row.Transported { + if strings.ToLower(so.Scope) == scope { + carries = true + break + } + } + if carries { + carrying++ + } else { + notCarrying++ + } + c := carries + row.CarriesScope = &c + out.Repeaters[i] = row + } + out.Carrying, out.NotCarry = &carrying, ¬Carrying + return &out +} + +// repeaterPubkeys lists every repeater and room this instance holds a nodes +// row for: the candidates the transport view attributes forwarding hops to. +func (db *DB) repeaterPubkeys() ([]string, error) { + rows, err := db.conn.Query(`SELECT public_key FROM nodes WHERE role IN ('repeater', 'room')`) + if err != nil { + return nil, fmt.Errorf("scope transport repeaters: %w", err) + } + defer rows.Close() + var out []string + for rows.Next() { + var pk string + if rows.Scan(&pk) == nil { + out = append(out, strings.ToLower(pk)) + } + } + return out, rows.Err() +} + +// computeScopeTransport builds one window's transport view (#2142): the same +// single forwarding scan as the declared view (ScopeAuditForwarding, same +// FLOOD-family route types and minimum hop length, ambiguous hops credited to +// nobody), with every known repeater as a target instead of only the ones that +// answered a declared-regions request. A repeater is listed when the scan +// attributed any forwarding to it in the window. +func (s *Server) computeScopeTransport(window, sinceISO string) (*ScopeTransportResponse, error) { + declaredByPK, targets, err := s.scopeTransportTargets() + if err != nil { + return nil, err + } + forwarding := map[string]*scopeAuditTargetAgg{} + if s.store != nil { + forwarding, err = s.store.ScopeAuditForwarding(sinceISO, targets) + if err != nil { + return nil, err + } + } + + seen := make([]string, 0, len(forwarding)) + for pk, agg := range forwarding { + if len(agg.scopes) > 0 || agg.unscopedPackets > 0 || agg.unmatchedPackets > 0 { + seen = append(seen, pk) + } + } + identities := s.db.scopeAuditNodeIdentities(seen) + + resp := &ScopeTransportResponse{Mode: "transport", Window: window, Since: sinceISO, Repeaters: []ScopeTransportRow{}} + for _, pk := range seen { + id := identities[pk] + if s.scopeTransportHidden(pk, id) { + continue + } + resp.Repeaters = append(resp.Repeaters, scopeTransportRow(pk, id, forwarding[pk], declaredByPK)) + } + sortScopeTransportRows(resp.Repeaters) + return resp, nil +} + +// scopeTransportTargets is every repeater the scan should attribute +// forwarding to: those that answered a declared-regions request and every +// known repeater, sorted, with the declared answers by key. +func (s *Server) scopeTransportTargets() (map[string]DeclaredRegionsRow, []string, error) { + declared, err := s.db.AllCurrentDeclaredRegions() + if err != nil { + return nil, nil, err + } + declaredByPK := make(map[string]DeclaredRegionsRow, len(declared)) + targetSet := make(map[string]bool, len(declared)) + for _, d := range declared { + pk := strings.ToLower(d.Target) + declaredByPK[pk] = d + targetSet[pk] = true + } + repeaters, err := s.db.repeaterPubkeys() + if err != nil { + return nil, nil, err + } + for _, pk := range repeaters { + targetSet[pk] = true + } + targets := make([]string, 0, len(targetSet)) + for pk := range targetSet { + targets = append(targets, pk) + } + sort.Strings(targets) + return declaredByPK, targets, nil +} + +// scopeTransportHidden applies the blacklist and hidden name prefixes. +func (s *Server) scopeTransportHidden(pk string, id scopeAuditNodeIdentity) bool { + if s.cfg == nil { + return false + } + return s.cfg.IsBlacklisted(pk) || (id.Name != nil && s.cfg.IsNameHidden(*id.Name)) +} + +// scopeTransportRow is one repeater's row: the scopes it was seen carrying, +// busiest first, and, when it answered a declared-regions request, what it +// declares and which of those it was not seen carrying. +func scopeTransportRow(pk string, id scopeAuditNodeIdentity, agg *scopeAuditTargetAgg, declaredByPK map[string]DeclaredRegionsRow) ScopeTransportRow { + transported := make([]ScopeObservation, 0, len(agg.scopes)) + for _, so := range agg.scopes { + transported = append(transported, *so) + } + sort.Slice(transported, func(i, j int) bool { + if transported[i].Packets != transported[j].Packets { + return transported[i].Packets > transported[j].Packets + } + return transported[i].Scope < transported[j].Scope + }) + row := ScopeTransportRow{ + PublicKey: pk, + Name: id.Name, + Role: id.Role, + Transported: transported, + UnscopedPackets: agg.unscopedPackets, + UnmatchedPackets: agg.unmatchedPackets, + AmbiguousHops: agg.ambiguousHops, + } + d, ok := declaredByPK[pk] + if !ok { + return row + } + named, wildcard := splitDeclaredRegions(d.RegionsCSV) + row.Asked = true + row.DeclaredRegions = named + row.DeclaredWildcard = wildcard + row.ConfigState = scopeAuditConfigState(named, wildcard) + row.DeclaredAt = d.ObservedAt + row.NotObserved = []string{} + for _, rgn := range named { + if agg.scopes[rgn] == nil { + row.NotObserved = append(row.NotObserved, rgn) + } + } + return row +} + +// sortScopeTransportRows orders rows by name, falling back to the key. +func sortScopeTransportRows(rows []ScopeTransportRow) { + label := func(r ScopeTransportRow) string { + if r.Name != nil && *r.Name != "" { + return *r.Name + } + return r.PublicKey + } + sort.Slice(rows, func(i, j int) bool { + if an, bn := label(rows[i]), label(rows[j]); an != bn { + return an < bn + } + return rows[i].PublicKey < rows[j].PublicKey + }) +} diff --git a/cmd/server/scope_stats_region_index_test.go b/cmd/server/scope_stats_region_index_test.go new file mode 100644 index 000000000..57a96e080 --- /dev/null +++ b/cmd/server/scope_stats_region_index_test.go @@ -0,0 +1,151 @@ +package main + +import ( + "database/sql" + "fmt" + "io" + "log" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// /api/scope-stats took 2.6 s on average on a production instance (17.7 s +// max). Four of its five queries take 10-100 ms there; the per-region count +// took 2.5-2.9 s for every window, even 1h, because SQLite chose +// idx_tx_scope_name (scope_name > '') and walked every scoped transmission in +// the database (45 days of them), filtering by first_seen afterwards. The +// window is the selective condition, so the query must stay on +// idx_transmissions_first_seen. + +// scopeStatsFixtureDB builds a database with the real schema (both indexes) +// holding numTx transmissions spread over 45 days, a quarter of them +// transport-scoped with a named region, as on the production instance. +func scopeStatsFixtureDB(tb testing.TB, numTx int) *DB { + tb.Helper() + log.SetOutput(io.Discard) + tb.Cleanup(func() { log.SetOutput(os.Stderr) }) + path := filepath.Join(tb.TempDir(), "scope-stats.db") + rw, err := sql.Open("sqlite3", path+"?_journal_mode=WAL") + if err != nil { + tb.Fatal(err) + } + // The tables and the two competing indexes as production has them: + // idx_transmissions_first_seen from the ingestor's base schema + // (cmd/ingestor/db.go), idx_tx_scope_name (partial) from + // dbschema.ensureScopeNameColumn. + for _, ddl := range []string{ + `CREATE TABLE transmissions (id INTEGER PRIMARY KEY AUTOINCREMENT, raw_hex TEXT NOT NULL, + hash TEXT NOT NULL UNIQUE, first_seen TEXT NOT NULL, route_type INTEGER, payload_type INTEGER, + payload_version INTEGER, decoded_json TEXT, from_pubkey TEXT, scope_name TEXT DEFAULT NULL)`, + `CREATE INDEX idx_transmissions_first_seen ON transmissions(first_seen)`, + `CREATE INDEX idx_transmissions_payload_type ON transmissions(payload_type)`, + `CREATE INDEX idx_transmissions_from_pubkey ON transmissions(from_pubkey)`, + `CREATE INDEX idx_tx_scope_name ON transmissions(scope_name) WHERE scope_name IS NOT NULL`, + `CREATE TABLE observations (id INTEGER PRIMARY KEY, transmission_id INTEGER, observer_id TEXT, + observer_name TEXT, direction TEXT, snr REAL, rssi REAL, score INTEGER, path_json TEXT, timestamp TEXT)`, + `CREATE TABLE observers (rowid INTEGER PRIMARY KEY, id TEXT, name TEXT, iata TEXT, inactive INTEGER)`, + `CREATE TABLE nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, + last_seen TEXT, first_seen TEXT, frequency REAL)`, + } { + if _, err := rw.Exec(ddl); err != nil { + tb.Fatalf("fixture schema: %v\n%s", err, ddl) + } + } + regions := []string{"#be", "#be-van", "#be-ant", "#be-gnt", "#be-lge", "#nl", "#nl-ams", "#de"} + now := time.Now().UTC() + if _, err := rw.Exec("BEGIN"); err != nil { + tb.Fatal(err) + } + stmt, err := rw.Prepare(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type, scope_name) + VALUES ('aa', ?, ?, ?, 5, ?)`) + if err != nil { + tb.Fatal(err) + } + // One step, computed once: i * 45 days in nanoseconds would overflow int64. + step := (45 * 24 * time.Hour) / time.Duration(numTx) + for i := 0; i < numTx; i++ { + ts := now.Add(-time.Duration(i) * step).Format(time.RFC3339) + var scope interface{} + route := 1 // FLOOD, unscoped by protocol + if i%4 == 0 { + route = 0 // TRANSPORT_FLOOD + scope = regions[i%len(regions)] + } + if _, err := stmt.Exec(fmt.Sprintf("h%08d", i), ts, route, scope); err != nil { + tb.Fatal(err) + } + } + stmt.Close() + if _, err := rw.Exec("COMMIT"); err != nil { + tb.Fatal(err) + } + if _, err := rw.Exec("ANALYZE"); err != nil { // production runs a bounded ANALYZE (#2072) + tb.Fatal(err) + } + rw.Close() + db, err := OpenDB(path) + if err != nil { + tb.Fatal(err) + } + tb.Cleanup(func() { db.Close() }) + return db +} + +func TestScopeStatsByRegion_UsesFirstSeenIndex(t *testing.T) { + db := scopeStatsFixtureDB(t, 40000) + since := time.Now().Add(-24 * time.Hour).UTC().Format(time.RFC3339) + rows, err := db.conn.Query("EXPLAIN QUERY PLAN "+scopeStatsByRegionQuery, since) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var plan []string + for rows.Next() { + var id, parent, notused int + var detail string + if err := rows.Scan(&id, &parent, ¬used, &detail); err != nil { + t.Fatal(err) + } + plan = append(plan, detail) + } + got := strings.Join(plan, " | ") + if !strings.Contains(got, "idx_transmissions_first_seen") || strings.Contains(got, "idx_tx_scope_name") { + t.Fatalf("per-region scope count must search the window on idx_transmissions_first_seen, plan: %s", got) + } +} + +func TestScopeStatsByRegion_CountsMatchWindow(t *testing.T) { + db := scopeStatsFixtureDB(t, 4000) + resp, err := db.GetScopeStats("24h") + if err != nil { + t.Fatal(err) + } + since := time.Now().Add(-24 * time.Hour).UTC().Format(time.RFC3339) + var want int + if err := db.conn.QueryRow(`SELECT COUNT(*) FROM transmissions WHERE route_type IN (0,3) + AND scope_name IS NOT NULL AND scope_name != '' AND first_seen >= ?`, since).Scan(&want); err != nil { + t.Fatal(err) + } + got := 0 + for _, rc := range resp.ByRegion { + got += rc.Count + } + if got != want || want == 0 { + t.Fatalf("byRegion sums to %d, window holds %d named-region transport transmissions", got, want) + } +} + +// BenchmarkGetScopeStats24h: the full /api/scope-stats query set for the 24h +// window on 300k transmissions over 45 days. +func BenchmarkGetScopeStats24h(b *testing.B) { + db := scopeStatsFixtureDB(b, 300000) + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, err := db.GetScopeStats("24h"); err != nil { + b.Fatal(err) + } + } +} diff --git a/cmd/server/scope_transport_2142_test.go b/cmd/server/scope_transport_2142_test.go new file mode 100644 index 000000000..7bd563bb8 --- /dev/null +++ b/cmd/server/scope_transport_2142_test.go @@ -0,0 +1,244 @@ +package main + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/gorilla/mux" +) + +// #2142: the scope audit lists only repeaters that answered a declared-regions +// request (17 of ~200 nodes on the instance that asked). The transport view +// lists every repeater seen forwarding in the window, with the region scopes +// it carried, its declared regions where known, and a scope filter (?scope=) +// that splits the fleet into carriers and non-carriers for rollout tracking. + +var testFullPubkeyC = "cccc" + strings.Repeat("33", 30) + +func getScopeTransport(t *testing.T, router *mux.Router, query string) ScopeTransportResponse { + t.Helper() + req := httptest.NewRequest("GET", "/api/scope-audit?mode=transport"+query, nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String()) + } + var got ScopeTransportResponse + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + return got +} + +func transportRow(t *testing.T, rows []ScopeTransportRow, pk string) ScopeTransportRow { + t.Helper() + for _, r := range rows { + if r.PublicKey == pk { + return r + } + } + t.Fatalf("no row for %s in %d rows", pk[:8], len(rows)) + return ScopeTransportRow{} +} + +func addRepeater(t *testing.T, srv *Server, pk, name string) { + t.Helper() + if _, err := srv.db.conn.Exec(`INSERT INTO nodes (public_key, name, role) VALUES (?, ?, 'repeater') + ON CONFLICT(public_key) DO UPDATE SET name = excluded.name, role = 'repeater'`, pk, name); err != nil { + t.Fatal(err) + } +} + +// seedTwoRepeaters: A declared "be" and carries #be; B never answered and +// carries #fr twice; C is a repeater with no traffic in the window. +func seedTwoRepeaters(t *testing.T, srv *Server) { + t.Helper() + now := time.Now().UTC() + insertDeclared(t, srv, testFullPubkeyA, now.Format(time.RFC3339), "be", 0) + addRepeater(t, srv, testFullPubkeyA, "Alpha") + addRepeater(t, srv, testFullPubkeyB, "Bravo") + addRepeater(t, srv, testFullPubkeyC, "Charlie") + recent := now.Add(-time.Minute).Format(time.RFC3339) + seedTransmissionRouteAt(t, srv.store, testFullPubkeyA[:4], scopeMatched("#be"), RouteFlood, recent) + seedTransmissionRouteAt(t, srv.store, testFullPubkeyB[:4], scopeMatched("#fr"), RouteFlood, recent) + seedTransmissionRouteAt(t, srv.store, testFullPubkeyB[:4], scopeMatched("#fr"), RouteFlood, recent) +} + +func TestScopeTransport_ListsRepeatersThatNeverAnswered(t *testing.T) { + srv, router := setupScopeAuditServer(t) + seedTwoRepeaters(t, srv) + got := getScopeTransport(t, router, "") + if got.Mode != "transport" { + t.Fatalf("mode = %q, want transport", got.Mode) + } + a := transportRow(t, got.Repeaters, testFullPubkeyA) + if !a.Asked || len(a.DeclaredRegions) != 1 || a.DeclaredRegions[0] != "be" { + t.Errorf("A: asked=%v declared=%v, want asked with [be]", a.Asked, a.DeclaredRegions) + } + if len(a.Transported) != 1 || a.Transported[0].Scope != "be" || a.Transported[0].Packets != 1 { + t.Errorf("A: transported = %+v, want be x1", a.Transported) + } + if len(a.NotObserved) != 0 { + t.Errorf("A: notObserved = %v, want none", a.NotObserved) + } + b := transportRow(t, got.Repeaters, testFullPubkeyB) + if b.Asked || b.DeclaredRegions != nil || b.NotObserved != nil { + t.Errorf("B: asked=%v declared=%v notObserved=%v, want not asked with null declared fields", b.Asked, b.DeclaredRegions, b.NotObserved) + } + if len(b.Transported) != 1 || b.Transported[0].Scope != "fr" || b.Transported[0].Packets != 2 { + t.Errorf("B: transported = %+v, want fr x2", b.Transported) + } + if b.Name == nil || *b.Name != "Bravo" { + t.Errorf("B: name = %v, want Bravo", b.Name) + } +} + +func TestScopeTransport_OmitsRepeatersNotSeenForwarding(t *testing.T) { + srv, router := setupScopeAuditServer(t) + seedTwoRepeaters(t, srv) + for _, r := range getScopeTransport(t, router, "").Repeaters { + if r.PublicKey == testFullPubkeyC { + t.Fatalf("C forwarded nothing in the window and must not be listed: %+v", r) + } + } +} + +func TestScopeTransport_ScopeFilterSplitsCarriers(t *testing.T) { + srv, router := setupScopeAuditServer(t) + seedTwoRepeaters(t, srv) + for _, q := range []string{"&scope=fr", "&scope=%23fr", "&scope=FR"} { + got := getScopeTransport(t, router, q) + if got.Scope != "fr" { + t.Errorf("%s: scope = %q, want normalised \"fr\"", q, got.Scope) + } + a := transportRow(t, got.Repeaters, testFullPubkeyA) + b := transportRow(t, got.Repeaters, testFullPubkeyB) + if a.CarriesScope == nil || *a.CarriesScope || b.CarriesScope == nil || !*b.CarriesScope { + t.Errorf("%s: carriesScope A=%v B=%v, want A false, B true", q, a.CarriesScope, b.CarriesScope) + } + if got.Carrying == nil || *got.Carrying != 1 || got.NotCarry == nil || *got.NotCarry != 1 { + t.Errorf("%s: carrying=%v notCarrying=%v, want 1 and 1", q, got.Carrying, got.NotCarry) + } + } + plain := getScopeTransport(t, router, "") + if plain.Scope != "" || plain.Carrying != nil || transportRow(t, plain.Repeaters, testFullPubkeyB).CarriesScope != nil { + t.Error("without a scope filter, no carriesScope or counts may be reported") + } +} + +func TestScopeTransport_FiltersBlacklistedRepeater(t *testing.T) { + srv, router := setupScopeAuditServer(t) + seedTwoRepeaters(t, srv) + srv.cfg.NodeBlacklist = []string{testFullPubkeyB} + for _, r := range getScopeTransport(t, router, "").Repeaters { + if r.PublicKey == testFullPubkeyB { + t.Fatal("blacklisted repeater must be excluded") + } + } +} + +func TestScopeAudit_RejectsUnknownMode(t *testing.T) { + _, router := setupScopeAuditServer(t) + req := httptest.NewRequest("GET", "/api/scope-audit?mode=bogus", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400 for an unknown mode", w.Code) + } +} + +func TestScopeTransport_CachedSeparatelyFromDeclaredView(t *testing.T) { + srv, router := setupScopeAuditServer(t) + seedTwoRepeaters(t, srv) + declared := getScopeAudit(t, router, "") + transport := getScopeTransport(t, router, "") + if len(declared.Repeaters) != 1 { + t.Fatalf("declared view = %d rows, want only the repeater that answered", len(declared.Repeaters)) + } + if len(transport.Repeaters) != 2 { + t.Fatalf("transport view = %d rows after the declared view was cached, want 2", len(transport.Repeaters)) + } +} + +// BenchmarkComputeScopeTransport: a fleet of 1,200 repeaters (#1975 quotes an +// instance with 1,179) and 30k flood transmissions in the last 24h, each +// forwarded along a 4-hop path of 3-byte prefixes, a third of them scoped to +// one of eight regions. Reports the response size too, as #2142 asks. +func BenchmarkComputeScopeTransport(b *testing.B) { + log.SetOutput(io.Discard) + b.Cleanup(func() { log.SetOutput(os.Stderr) }) + conn, err := sql.Open("sqlite3", ":memory:") + if err != nil { + b.Fatal(err) + } + conn.SetMaxOpenConns(1) + for _, ddl := range []string{ + `CREATE TABLE transmissions (id INTEGER PRIMARY KEY AUTOINCREMENT, raw_hex TEXT NOT NULL, hash TEXT NOT NULL UNIQUE, + first_seen TEXT NOT NULL, route_type INTEGER, payload_type INTEGER, code1 TEXT, code2 TEXT, scope_name TEXT)`, + `CREATE INDEX idx_transmissions_first_seen ON transmissions(first_seen)`, + `CREATE TABLE observations (id INTEGER PRIMARY KEY AUTOINCREMENT, transmission_id INTEGER NOT NULL, path_json TEXT, timestamp INTEGER NOT NULL)`, + `CREATE INDEX idx_obs_tx ON observations(transmission_id)`, + `CREATE TABLE nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT, configured_scope TEXT, configured_scope_at TEXT)`, + } { + if _, err := conn.Exec(ddl); err != nil { + b.Fatal(err) + } + } + db := &DB{conn: conn} + if err := db.detectSchema(context.Background(), conn); err != nil { + b.Fatal(err) + } + const fleet = 1200 + pks := make([]string, fleet) + conn.Exec("BEGIN") + for i := range pks { + pks[i] = fmt.Sprintf("%06x", i*13+0x100000) + strings.Repeat("ab", 29) + scope := sql.NullString{} + if i%7 == 0 { + scope = sql.NullString{String: "be,be-van,*", Valid: true} + } + conn.Exec(`INSERT INTO nodes (public_key, name, role, configured_scope, configured_scope_at) VALUES (?, ?, 'repeater', ?, ?)`, + pks[i], fmt.Sprintf("Repeater %d", i), scope, time.Now().UTC().Format(time.RFC3339)) + } + regions := []string{"#be", "#be-van", "#be-ant", "#be-gnt", "#be-lge", "#nl", "#nl-ams", "#de"} + now := time.Now().UTC() + for i := 0; i < 30000; i++ { + var scope interface{} + route := RouteFlood + if i%3 == 0 { + route, scope = 0, regions[i%len(regions)] + } + res, _ := conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type, code1, code2, scope_name) + VALUES ('AA', ?, ?, ?, 1, '1234', '00', ?)`, fmt.Sprintf("bench%d", i), now.Add(-time.Duration(i)*2*time.Second).Format(time.RFC3339), route, scope) + id, _ := res.LastInsertId() + path := fmt.Sprintf(`["%s","%s","%s","%s"]`, strings.ToUpper(pks[i%fleet][:6]), strings.ToUpper(pks[(i*7)%fleet][:6]), + strings.ToUpper(pks[(i*11)%fleet][:6]), strings.ToUpper(pks[(i*17)%fleet][:6])) + conn.Exec(`INSERT INTO observations (transmission_id, path_json, timestamp) VALUES (?, ?, ?)`, id, path, now.Unix()) + } + conn.Exec("COMMIT") + cfg := &Config{Port: 3000} + srv := NewServer(db, cfg, NewHub()) + srv.store = newTestStoreWithDB(b, db, cfg) + since := now.Add(-24 * time.Hour).Format(time.RFC3339) + b.ResetTimer() + var resp *ScopeTransportResponse + for i := 0; i < b.N; i++ { + if resp, err = srv.computeScopeTransport("24h", since); err != nil { + b.Fatal(err) + } + } + b.StopTimer() + body, _ := json.Marshal(resp) + b.ReportMetric(float64(len(resp.Repeaters)), "rows") + b.ReportMetric(float64(len(body))/1024, "response-KB") +} diff --git a/cmd/server/store.go b/cmd/server/store.go index 2d9552850..c2c4c5eb4 100644 --- a/cmd/server/store.go +++ b/cmd/server/store.go @@ -295,10 +295,12 @@ type PacketStore struct { // Precomputed subpath index: raw comma-joined hops → occurrence count. // Built during Load(), incrementally updated on ingest. Avoids full // packet iteration at query time (O(unique_subpaths) vs O(total_packets)). - spIndex map[string]int // "hop1,hop2" → count - spTxIndex map[string][]*StoreTx // "hop1,hop2" → transmissions containing this subpath - spTotalPaths int // transmissions with paths >= 2 hops - // Background-build ready gates for spIndex/spTxIndex and byPathHop + // "hop1,hop2" → transmissions containing this subpath, one entry per + // occurrence. The subpath's count is len(spTxIndex[key]); a separate + // key → count map used to hold the same 1M+ keys a second time. + spTxIndex map[string][]*StoreTx + spTotalPaths int // transmissions with paths >= 2 hops + // Background-build ready gates for spTxIndex and byPathHop // (#1008). Flipped from false→true exactly once by the goroutine // kicked off in Load() (or synchronously by the background chunk // loader). Handlers gate reads via SubpathIndexReady() / @@ -740,7 +742,6 @@ func NewPacketStore(db *DB, cfg *PacketStoreConfig, cacheTTLs ...map[string]inte rfCacheTTL: 60 * time.Second, collisionCacheTTL: 3600 * time.Second, invCooldown: 300 * time.Second, - spIndex: make(map[string]int, 4096), spTxIndex: make(map[string][]*StoreTx, 4096), advertPubkeys: make(map[string]int), pathHopResolved: make(map[*StoreTx][]string), @@ -1145,7 +1146,7 @@ func (s *PacketStore) Load() error { // The chunk is assumed to be older than the data already in the store, so // localPackets are prepended to s.packets. // -// byPayloadType is updated here incrementally. byPathHop, spIndex, and +// byPayloadType is updated here incrementally. byPathHop, spTxIndex and // distHops are NOT updated here — the caller (loadBackgroundChunks) rebuilds // those once after all chunks are merged. @@ -3046,7 +3047,7 @@ func (s *PacketStore) IngestNewFromDB(sinceID, limit int) ([]map[string]interfac // Incrementally update precomputed subpath index with new transmissions for _, tx := range broadcastTxs { - if addTxToSubpathIndexFull(s.spIndex, s.spTxIndex, tx) { + if addTxToSubpathIndex(s.spTxIndex, tx) { s.spTotalPaths++ } addTxToPathHopIndex(s.byPathHop, tx) @@ -3449,7 +3450,7 @@ func (s *PacketStore) IngestNewObservations(sinceObsID, limit int) []map[string] // Temporarily set parsedPath to old hops for removal. saved, savedFlag := tx.parsedPath, tx.pathParsed tx.parsedPath, tx.pathParsed = oldHops, true - if removeTxFromSubpathIndexFull(s.spIndex, s.spTxIndex, tx) { + if removeTxFromSubpathIndex(s.spTxIndex, tx) { s.spTotalPaths-- } tx.parsedPath, tx.pathParsed = saved, savedFlag @@ -3464,7 +3465,7 @@ func (s *PacketStore) IngestNewObservations(sinceObsID, limit int) []map[string] } // pickBestObservation already set pathParsed=false so // addTxToSubpathIndex will re-parse the new path. - if addTxToSubpathIndexFull(s.spIndex, s.spTxIndex, tx) { + if addTxToSubpathIndex(s.spTxIndex, tx) { s.spTotalPaths++ } addTxToPathHopIndex(s.byPathHop, tx) @@ -3598,7 +3599,7 @@ func (s *PacketStore) filterPackets(q PacketQuery, nodePK string) []*StoreTx { // Pre-compute area node set. var areaNodes map[string]bool - if q.Area != "" { + if q.Area != "" && q.startedIn == nil { areaNodes = s.resolveAreaNodes(q.Area) } @@ -3667,10 +3668,14 @@ func (s *PacketStore) filterPackets(q PacketQuery, nodePK string) []*StoreTx { return false } } + if q.startedIn != nil && !q.startedIn(tx.Hash) { + return false + } if areaNodes != nil { // Only ADVERT packets carry the originator pubkey (public_key/pubKey). // All other packet types (GRP_TXT, TXT_MSG, REQ, …) have encrypted - // senders so pk == "" and are excluded when an area filter is active. + // senders so pk == "" and are excluded when an area filter is active, + // unless the Data tab places them (startedIn above). d := tx.ParsedDecoded() pk, _ := d["public_key"].(string) if pk == "" { @@ -3860,12 +3865,18 @@ const areaNodeTTL = 30 * time.Second // TTL is served as-is while one background refresh re-queries it (#2146). // Uses its own RWMutex so callers holding s.mu won't deadlock. func (s *PacketStore) resolveAreaNodes(areaKey string) map[string]bool { - if s.config == nil || s.config.Areas == nil { + if s.config == nil { return nil } entry, ok := s.config.Areas[areaKey] if !ok { - return nil + if !s.config.fileArea(areaKey) { + return nil + } + // An area from areasFile: matched by position against its GeoJSON + // geometry, through the same cache as config.json's areas. + m := s.config.areaMap + entry = AreaEntry{match: func(lat, lon float64) bool { return m.Contains(areaKey, lat, lon) }} } s.areaNodeMu.RLock() @@ -4256,16 +4267,10 @@ func txGetParsedPath(tx *StoreTx) []string { return tx.parsedPath } -// addTxToSubpathIndex extracts all raw subpaths (lengths 2–8) from tx and -// increments their counts in the index. Returns true if the tx contributed -// (path had ≥ 2 hops). -func addTxToSubpathIndex(idx map[string]int, tx *StoreTx) bool { - return addTxToSubpathIndexFull(idx, nil, tx) -} - -// addTxToSubpathIndexFull is like addTxToSubpathIndex but also appends -// tx to txIdx for each subpath key (if txIdx is non-nil). -func addTxToSubpathIndexFull(idx map[string]int, txIdx map[string][]*StoreTx, tx *StoreTx) bool { +// addTxToSubpathIndex appends tx to txIdx under every raw subpath (lengths +// 2–8) of its path, once per occurrence, so len(txIdx[key]) is the subpath's +// count. Returns true if the tx contributed (path had ≥ 2 hops). +func addTxToSubpathIndex(txIdx map[string][]*StoreTx, tx *StoreTx) bool { hops := txGetParsedPath(tx) if len(hops) < 2 { return false @@ -4274,25 +4279,16 @@ func addTxToSubpathIndexFull(idx map[string]int, txIdx map[string][]*StoreTx, tx for l := 2; l <= maxL; l++ { for start := 0; start <= len(hops)-l; start++ { key := strings.ToLower(strings.Join(hops[start:start+l], ",")) - idx[key]++ - if txIdx != nil { - txIdx[key] = append(txIdx[key], tx) - } + txIdx[key] = append(txIdx[key], tx) } } return true } -// removeTxFromSubpathIndex is the inverse of addTxToSubpathIndex — it -// decrements counts for all raw subpaths of tx. Returns true if the tx -// had a path. -func removeTxFromSubpathIndex(idx map[string]int, tx *StoreTx) bool { - return removeTxFromSubpathIndexFull(idx, nil, tx) -} - -// removeTxFromSubpathIndexFull is like removeTxFromSubpathIndex but also -// removes tx from txIdx for each subpath key (if txIdx is non-nil). -func removeTxFromSubpathIndexFull(idx map[string]int, txIdx map[string][]*StoreTx, tx *StoreTx) bool { +// removeTxFromSubpathIndex is the inverse of addTxToSubpathIndex: it removes +// one occurrence of tx per raw subpath of its path, and drops keys left +// empty. Returns true if the tx had a path. +func removeTxFromSubpathIndex(txIdx map[string][]*StoreTx, tx *StoreTx) bool { hops := txGetParsedPath(tx) if len(hops) < 2 { return false @@ -4301,40 +4297,35 @@ func removeTxFromSubpathIndexFull(idx map[string]int, txIdx map[string][]*StoreT for l := 2; l <= maxL; l++ { for start := 0; start <= len(hops)-l; start++ { key := strings.ToLower(strings.Join(hops[start:start+l], ",")) - idx[key]-- - if idx[key] <= 0 { - delete(idx, key) - } - if txIdx != nil { - txs := txIdx[key] - for i, t := range txs { - if t == tx { - txIdx[key] = append(txs[:i], txs[i+1:]...) - break - } - } - if len(txIdx[key]) == 0 { - delete(txIdx, key) + txs := txIdx[key] + for i, t := range txs { + if t == tx { + txs = append(txs[:i], txs[i+1:]...) + break } } + if len(txs) == 0 { + delete(txIdx, key) + } else { + txIdx[key] = txs + } } } return true } -// buildSubpathIndex scans all packets and populates spIndex + spTotalPaths. +// buildSubpathIndex scans all packets and populates spTxIndex + spTotalPaths. // Must be called with s.mu held. func (s *PacketStore) buildSubpathIndex() { - s.spIndex = make(map[string]int, 4096) s.spTxIndex = make(map[string][]*StoreTx, 4096) s.spTotalPaths = 0 for _, tx := range s.packets { - if addTxToSubpathIndexFull(s.spIndex, s.spTxIndex, tx) { + if addTxToSubpathIndex(s.spTxIndex, tx) { s.spTotalPaths++ } } log.Printf("[store] Built subpath index: %d unique raw subpaths from %d paths", - len(s.spIndex), s.spTotalPaths) + len(s.spTxIndex), s.spTotalPaths) } // buildPathHopIndex rebuilds byPathHop: raw wire hops from every packet's @@ -5174,7 +5165,7 @@ func (s *PacketStore) evictStaleInternal(rpBatch map[int][]string) int { s.removeFromResolvedPubkeyIndex(tx.ID) // Remove from subpath index - removeTxFromSubpathIndexFull(s.spIndex, s.spTxIndex, tx) + removeTxFromSubpathIndex(s.spTxIndex, tx) } // Sweep raw AND resolved hop keys once per batch (#1908). The hash-only // membership index cannot recover full pubkey strings. Reuse the evicted @@ -5433,7 +5424,7 @@ func hasUpperASCII(s string) bool { // loops that resolve hops outside any per-tx scope (subpath/topology // aggregations). Caller passes the slice of txs to consider; we union the // per-tx contexts with de-dup. Used by call sites that read from precomputed -// indices (s.spIndex, s.spTxIndex) or that resolve user-supplied hops. +// indices (s.spTxIndex) or that resolve user-supplied hops. // // Result is order-independent in semantics; iteration order is deterministic // only modulo Go's map iteration (acceptable — the resolver's tier-2 averages @@ -10325,7 +10316,7 @@ func (s *PacketStore) GetNodeAnalytics(pubkey string, days int) (*NodeAnalyticsR // path. With a zero TimeWindow this is byte-equivalent to GetAnalyticsSubpaths. // // For non-zero windows we iterate the packet list and filter on -// `tx.FirstSeen`. We deliberately do not consult the precomputed `spIndex` +// `tx.FirstSeen`. We deliberately do not consult the precomputed `spTxIndex` // (which has no per-tx timestamp), so the windowed path is O(N_tx · path²); // this matches the slow region-filtered path and keeps the fast unbounded // hot path untouched. Results are cached by (region|area|window) so repeated @@ -10531,7 +10522,8 @@ func (s *PacketStore) GetAnalyticsSubpathsBulk(region string, groups []subpathGr perGroup[i] = make(map[string]*subpathAccum) } - for rawKey, count := range s.spIndex { + for rawKey, txs := range s.spTxIndex { + count := len(txs) hops := strings.Split(rawKey, ",") hopLen := len(hops) @@ -10591,7 +10583,7 @@ func (s *PacketStore) computeAnalyticsSubpaths(region string, minLen, maxLen, li _, pm := s.getCachedNodesAndPM() // Aggregate hop-disambiguation context across all packets — bulk - // aggregator over s.spIndex / per-tx fallback both need it. See #1197. + // aggregator over s.spTxIndex / per-tx fallback both need it. See #1197. contextPubkeys := buildAggregateHopContextPubkeys(s.packets, pm) hopCache := make(map[string]*nodeInfo) graph := s.graph.Load() // hoist out of resolver closure (PR #1208 carmack #1) @@ -10618,8 +10610,9 @@ func (s *PacketStore) computeAnalyticsSubpaths(region string, minLen, maxLen, li // Fast path: read from precomputed raw-hop subpath index. // Resolve raw hop prefixes to names and merge counts. - namedCounts := make(map[string]*subpathAccum, len(s.spIndex)) - for rawKey, count := range s.spIndex { + namedCounts := make(map[string]*subpathAccum, len(s.spTxIndex)) + for rawKey, txs := range s.spTxIndex { + count := len(txs) hops := strings.Split(rawKey, ",") hopLen := len(hops) if hopLen < minLen || hopLen > maxLen { diff --git a/cmd/server/subpath_index_memory_test.go b/cmd/server/subpath_index_memory_test.go new file mode 100644 index 000000000..3f0c8ec74 --- /dev/null +++ b/cmd/server/subpath_index_memory_test.go @@ -0,0 +1,162 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "log" + "math/rand" + "os" + "runtime" + "testing" +) + +// The subpath index holds every contiguous run of 2-8 hops of every stored +// transmission's path. On a production instance's 7-day window (41k +// transmissions with 2+ hops) that is 1.2M distinct keys, 79% of them seen +// once, and 3.07M entries; a heap profile put 186 MB of a 805 MB live heap in +// addTxToSubpathIndexFull. +// +// subpathFixture builds transmissions with that shape from synthetic data: path +// lengths follow the production hop-count histogram, and hops are random walks +// over a 400-node graph with 3-byte (6 hex) prefixes, which gives the same +// key-reuse profile (about 80% of keys seen once). +func subpathFixture(numTx int, seed int64) []*StoreTx { + rng := rand.New(rand.NewSource(seed)) + const nodes = 400 + prefixes, neighbours := subpathGraph(rng, nodes) + // Hop-count histogram from production (lengths 2..19, then 20 = "20 or more"). + weights := []int{2086, 1394, 1142, 1181, 1396, 2287, 3256, 2595, 2686, 2590, 2079, 2035, 1831, 1413, 1294, 1148, 978, 850, 9107} + txs := make([]*StoreTx, numTx) + for i := range txs { + n := weightedHopCount(rng, weights) + at := rng.Intn(nodes) + hops := make([]string, n) + for h := 0; h < n; h++ { + hops[h] = prefixes[at] + at = neighbours[at][rng.Intn(len(neighbours[at]))] + } + pj, _ := json.Marshal(hops) + txs[i] = &StoreTx{ID: i + 1, PathJSON: string(pj)} + } + return txs +} + +// subpathGraph is a random graph of n nodes with 3-byte prefixes and six +// neighbours each. +func subpathGraph(rng *rand.Rand, n int) ([]string, [][]int) { + prefixes := make([]string, n) + neighbours := make([][]int, n) + for i := range prefixes { + prefixes[i] = fmt.Sprintf("%06X", rng.Intn(1<<24)) + for k := 0; k < 6; k++ { + neighbours[i] = append(neighbours[i], rng.Intn(n)) + } + } + return prefixes, neighbours +} + +// weightedHopCount draws a path length from the histogram: weights[i] is the +// weight of length i+2, and the last bucket stands for 20-44 hops. +func weightedHopCount(rng *rand.Rand, weights []int) int { + total := 0 + for _, w := range weights { + total += w + } + r := rng.Intn(total) + for i, w := range weights { + if r < w { + if i == len(weights)-1 { + return 20 + rng.Intn(25) // long floods: 20-44 hops + } + return i + 2 + } + r -= w + } + return 2 +} + +// buildSubpathIndexForTest builds the index the way Load does and returns it. +func buildSubpathIndexForTest(txs []*StoreTx) *PacketStore { + s := &PacketStore{packets: txs} + s.buildSubpathIndex() + return s +} + +// retainedHeapMB reports how much live heap build() keeps after a full GC. +func retainedHeapMB(build func() interface{}) float64 { + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + keep := build() + runtime.GC() + runtime.ReadMemStats(&after) + runtime.KeepAlive(keep) + return float64(int64(after.HeapAlloc)-int64(before.HeapAlloc)) / (1 << 20) +} + +func TestSubpathFixtureShape(t *testing.T) { + txs := subpathFixture(20000, 1) + keys := map[string]int{} + for _, tx := range txs { + hops := txGetParsedPath(tx) + for l := 2; l <= min(8, len(hops)); l++ { + for s := 0; s+l <= len(hops); s++ { + keys[fmt.Sprint(hops[s:s+l])]++ + } + } + } + once := 0 + for _, c := range keys { + if c == 1 { + once++ + } + } + share := float64(once) / float64(len(keys)) + t.Logf("fixture: %d txs, %d distinct subpath keys, %.0f%% seen once", len(txs), len(keys), share*100) + if share < 0.6 || share > 0.95 { + t.Fatalf("fixture no longer resembles production key reuse (%.0f%% seen once, production 79%%)", share*100) + } +} + +// BenchmarkBuildSubpathIndex reports the live heap the index keeps for a +// production-shaped 7-day window (41k transmissions with paths). +// +// go test -run '^$' -bench BenchmarkBuildSubpathIndex -count 10 ./cmd/server +func BenchmarkBuildSubpathIndex(b *testing.B) { + log.SetOutput(io.Discard) + b.Cleanup(func() { log.SetOutput(os.Stderr) }) + txs := subpathFixture(41000, 1) + for _, tx := range txs { + txGetParsedPath(tx) // parse once, outside the measurement + } + b.ReportAllocs() + b.ResetTimer() + var mb float64 + for i := 0; i < b.N; i++ { + mb = retainedHeapMB(func() interface{} { return buildSubpathIndexForTest(txs) }) + } + b.ReportMetric(mb, "retained-MB") +} + +// TestSubpathIndexRetainedHeap bounds the live heap the subpath index keeps for +// the production-shaped fixture. It kept 250 MB when a separate key → count +// map duplicated every key of spTxIndex; with counts read as len(txs) it keeps +// about 197 MB. The bound sits between the two. +func TestSubpathIndexRetainedHeap(t *testing.T) { + if testing.Short() { + t.Skip("builds a 1.5M-key index") + } + log.SetOutput(io.Discard) + defer log.SetOutput(os.Stderr) + txs := subpathFixture(41000, 1) + for _, tx := range txs { + txGetParsedPath(tx) + } + const limitMB = 225 + mb := retainedHeapMB(func() interface{} { return buildSubpathIndexForTest(txs) }) + t.Logf("subpath index for 41k production-shaped transmissions keeps %.1f MB", mb) + if mb > limitMB { + t.Fatalf("subpath index keeps %.1f MB, limit %d MB", mb, limitMB) + } +} diff --git a/cmd/server/subpaths_window_test.go b/cmd/server/subpaths_window_test.go index 933dbff64..1d7c38c6c 100644 --- a/cmd/server/subpaths_window_test.go +++ b/cmd/server/subpaths_window_test.go @@ -2,7 +2,7 @@ package main // Regression test for issue #1217 — Route Patterns analytics must honor the // `?window=` time-window filter (e.g. "1h", "24h", "7d"). Before the fix, -// computeAnalyticsSubpaths read the full s.spIndex / s.packets regardless of +// computeAnalyticsSubpaths read the full s.spTxIndex / s.packets regardless of // the window, so the chart counts were identical for every window selection. // // This test seeds two transmissions with distinct multi-hop paths at different @@ -63,7 +63,7 @@ func TestSubpathsHonorsTimeWindow_StoreLevel(t *testing.T) { t.Fatalf("store.Load failed: %v", err) } // #1008: indexes build in the background after Load(); tests that - // read s.spIndex / s.spTxIndex must wait for the ready flag. + // read s.spTxIndex must wait for the ready flag. if !store.WaitIndexesReady(5 * time.Second) { t.Fatalf("indexes not ready after 5s") } diff --git a/cmd/server/types.go b/cmd/server/types.go index 08acf1b92..48b29feb3 100644 --- a/cmd/server/types.go +++ b/cmd/server/types.go @@ -1,5 +1,7 @@ package main +import "github.com/meshcore-analyzer/dataindex" + // Types generated from proto/ definitions for compile-time type safety. // Every API response is a typed struct — no map[string]interface{}. @@ -408,6 +410,8 @@ type PacketDetailResponse struct { Path []interface{} `json:"path"` ObservationCount int `json:"observation_count"` Observations []ObservationResp `json:"observations,omitempty"` + // Origin is where the packet started, when the Data tab places packets. + Origin *dataindex.Origin `json:"origin,omitempty"` } type DecodeResponse struct { diff --git a/cmd/server/user_mgmt_config.go b/cmd/server/user_mgmt_config.go index 6683685d0..236a26354 100644 --- a/cmd/server/user_mgmt_config.go +++ b/cmd/server/user_mgmt_config.go @@ -86,6 +86,17 @@ type NotificationsConfig struct { PerUserPerDay int `json:"perUserPerDay,omitempty"` MaxMailsPerDay int `json:"maxMailsPerDay,omitempty"` MaxWatchesPerUser int `json:"maxWatchesPerUser,omitempty"` + // ExternalAlerts feeds the node.external event (#2177). Absent: the + // event is not offered. + ExternalAlerts *ExternalAlertsConfig `json:"externalAlerts,omitempty"` +} + +// ExternalAlertsConfig is userManagement.notifications.externalAlerts: a +// JSON feed of per-node alerts computed outside CoreScope. +type ExternalAlertsConfig struct { + URL string `json:"url"` + MaxAgeHours int `json:"maxAgeHours,omitempty"` + Label string `json:"label,omitempty"` } // notifySettings is the resolved form; the zero value means off. @@ -95,6 +106,38 @@ type notifySettings struct { perUserPerDay int // notification mails per user per 24 hours maxMailsPerDay int // notification mails per instance per 24 hours maxWatchesPerUser int + external externalAlertSettings +} + +// externalAlertSettings is the resolved externalAlerts block; url "" means +// not configured. +type externalAlertSettings struct { + url string + maxAge time.Duration // a feed generated longer ago is stale + label string // names the source in mail lines and on the account page +} + +const ( + defaultExternalAlertsMaxAgeHours = 48 + defaultExternalAlertsLabel = "External alert" +) + +// resolveExternalAlerts validates the externalAlerts block and fills the +// defaults; nil gives the zero value (not configured). +func resolveExternalAlerts(c *ExternalAlertsConfig) (externalAlertSettings, error) { + if c == nil { + return externalAlertSettings{}, nil + } + u, err := url.Parse(strings.TrimSpace(c.URL)) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + return externalAlertSettings{}, errors.New("userManagement.notifications.externalAlerts.url must be an absolute http(s) URL") + } + label := mailSafeText(c.Label) + if label == "" { + label = defaultExternalAlertsLabel + } + return externalAlertSettings{url: u.String(), label: label, + maxAge: time.Duration(positiveOr(c.MaxAgeHours, defaultExternalAlertsMaxAgeHours)) * time.Hour}, nil } const ( @@ -256,6 +299,11 @@ func resolveUserManagement(u *UserManagementConfig, measurementDBPath string, ge } set.proposals = resolveProposals(u.ChannelProposals) set.notify = resolveNotifications(u.Notifications) + if set.notify.enabled { + if set.notify.external, err = resolveExternalAlerts(u.Notifications.ExternalAlerts); err != nil { + return nil, err + } + } set.backup = resolveBackup(u.Backup, set.dbPath) return set, nil } diff --git a/config.example.json b/config.example.json index 00bb029c9..3ae31b885 100644 --- a/config.example.json +++ b/config.example.json @@ -272,6 +272,17 @@ "mode": "flag", "_comment": "Controls how the ingestor handles ADVERTs whose GPS is OUTSIDE the geo_filter polygon (#730). 'flag' (default): store the advert/node and tag it foreign_advert=1 so operators can see bridged/leaked nodes via the API ('foreign': true on /api/nodes). 'drop': legacy behavior — silently discard the advert (no log, no node row). Only applies when geo_filter is configured; otherwise has no effect." }, + "_comment_areasFile": "Optional. A GeoJSON FeatureCollection of further areas, path relative to this file (or absolute). Use it for real boundaries that the polygons below cannot hold: coastlines, islands (MultiPolygon) and holes. Each feature is one area; its properties are code (required, unique across every area including those below), label, layer (default \"region\"; one file can hold several sets, such as countries and counties) and iata (airport codes of observers that report no position, so they still belong to an area). Coordinates are GeoJSON's [lon, lat]. Its areas join the area filter beside the ones below. A missing or invalid file stops the server at startup. Example: docs/examples/areas.example.geojson.", + "areasFile": "", + "_comment_data": "Optional. The Data tab: every packet of the last few days placed by the area it STARTED in (its advert's GPS, the sender's node, the first repeater of 2+ bytes, or the observer that heard it with no relay) and the areas whose observers heard it, with filters, charts, a who-hears-whom matrix and the packets behind any figure. Areas (areasFile or areas) are optional: without them the tab still counts by kind, type, channel, scope and routing, leaves out the place views (from, heard in, through, crossed a border, how it arrived), and refuses homeArea and any dashboard that needs places. enabled: off by default. days: history held, default 7, at most 30 (about 0.7 MB per 10,000 packets a day). layer: the areasFile layer to place packets in, default the first layer. homeArea: optional area code; flows then report the home relays at each boundary and how much went via home, and it is the default of a dashboard's $home variable. dashboardsFile: optional JSON file (relative to this one) listing ready-made dashboards for every visitor, exactly as the tab's Export saves them; validated at startup, a bad file stops the server with the reason. defaultDashboard: id of the dashboard the tab opens on (default: the built-in Overview).", + "data": { + "enabled": false, + "days": 7, + "layer": "", + "homeArea": "", + "dashboardsFile": "", + "defaultDashboard": "" + }, "areas": { "_comment": "Optional. GPS-based display filter. Each entry defines a geographic area by polygon ([lat, lon] pairs) or bounding box (latMin/latMax/lonMin/lonMax). Packets and nodes are attributed to an area based on the transmitting node's own GPS coordinates — not the observer's location. Areas appear as a filter pill bar in the dashboard. Remove this section to disable the area filter UI.", "BAY": { @@ -404,6 +415,10 @@ "_comment_hashRegions": "Region names for scope matching on transport-route packets. Key = SHA256('#name')[:16]. Add any region names used by nodes in your network.", "autoRegionKeys": { "enabled": false, "maxDerived": 256, "refreshMinutes": 15 }, "_comment_autoRegionKeys": "Opt-in: derive region keys from the region names nodes are CONFIRMED to be configured for, on top of the explicit hashRegions list above. Default OFF, and an absent block leaves behaviour unchanged. Sources: nodes.configured_scope (written by the observer /neighbors ingestion) and, where a deployment fills it, the optional node_declared_regions table. Solves the case where a repeater forwards a region this instance holds no key for: its traffic is stored unmatched, and anything comparing declared against observed reports the region as absent rather than unnameable. TOP-LEVEL FLAG, a sibling of hashRegions: config loading is plain json.Unmarshal with no DisallowUnknownFields, so nesting it elsewhere is silently ignored and the feature stays off with no error. maxDerived caps the derived tier (default 256): each key costs one HMAC per transport-scoped packet and raises the random 2-byte collision rate by 1/65536, and the match cannot be indexed because the code is an HMAC over the payload. Over the cap, names are kept by how many distinct nodes declare them, so a one-off local name is dropped before a region half the network uses. refreshMinutes is how often the derived tier is rebuilt (default 15).", + "regionQuickPicks": [ + { "name": "Northern California", "description": "Bay Area and Sacramento observers.", "regions": ["SJC", "SFO", "OAK", "SMF"] } + ], + "_comment_regionQuickPicks": "Optional. Named groups of region (IATA) codes shown as one-tap buttons beside the region filter on every page that has one. A tap selects the group's codes that currently have an observer; tapping it again goes back to all regions, and the filter button then shows the group's name. List every code that belongs to the group, including ones with no observer yet: they cost nothing and are picked up as soon as an observer appears. A group with no observer at all is not shown. Like every region filter, a group means 'heard by observers in these regions', not 'located there'. name is required; description is the button's tooltip. Up to 20 groups of 200 codes; codes are upper-cased and de-duplicated.", "_comment_defaultRegion": "IATA code shown by default in region filters.", "_comment_mapDefaults": "Initial map center [lat, lon] and zoom level.", "_comment_regions": "IATA code → display name mapping for the region filter UI. Each key is a 3-letter IATA code that an observer is tagged with (resolved priority: MQTT payload `region` field > topic-derived region > mqttSources.region). Observers without an IATA tag will not appear under any region filter — only under 'All Regions'. The region filter dropdown shows one entry per code listed here PLUS any extra IATA codes the server discovers from observers at runtime (so you can omit codes here and they will still be selectable, just labelled with the bare IATA code instead of a friendly name). Selecting 'All Regions' (or no region) returns results from every observer including those with no IATA tag; selecting one or more codes restricts results to packets observed by observers tagged with those codes. The reserved value 'All' (case-insensitive) is treated as 'no filter' on the server, so the URL ?region=All behaves identically to omitting the param. Issue #770.", @@ -465,7 +480,7 @@ }, "_comment_userManagement": "Optional accounts (off by default; see docs/user-guide/accounts.md). When enabled: visitors can register with email + password and activate through a mailed link; addresses in adminEmails become admins; admins manage users at #/admin/users and can use the operator endpoints without the apiKey. The dashboard stays public. dbPath defaults to users.db next to the analyzer database: a separate file, the server never writes measurement data. publicBaseUrl is required and is used for every link in every mail. Mail goes through Brevo's transactional API (a free account is enough); brevoApiKey and webhookSecret may instead come from CORESCOPE_BREVO_API_KEY and CORESCOPE_BREVO_WEBHOOK_SECRET. Set webhookSecret (16+ chars) and point a Brevo transactional webhook at /api/mail/brevo/webhook with bearer auth to see delivery status per user. trustedProxies (CIDRs) lets login rate limits use X-Forwarded-For behind a reverse proxy. Startup fails if enabled with an incomplete mail setup.", "_comment_channelProposals": "Optional, needs userManagement.enabled (docs/user-guide/accounts.md, Channel proposals). Logged-in users propose hashtag channels; admins approve, reject or revoke them on the Proposals tab. An approved channel is decrypted by the ingestor from its next refresh (once a minute, no restart) and listed for every visitor on the Channels page. maxApproved bounds the decryption work (every approved key is tried on every group message); perUserPerDay and maxPending limit proposals. The ingestor reads users.db read-only from userManagement.dbPath, or next to the analyzer database; set dbPath explicitly when the server and the ingestor are not given the same analyzer database path.", - "_comment_notifications": "Optional, needs userManagement.enabled (docs/user-guide/accounts.md, Node notifications). Logged-in users watch nodes and get one mail per check when a watched node goes offline, comes back or reports a low battery; admins can also watch for new foreign nodes and observers going offline. Thresholds are healthThresholds and batteryThresholds. A check runs every intervalMinutes; at most perUserPerDay mails per user and maxMailsPerDay in total go out per 24 hours (over a limit the change is recorded and dropped, never queued). maxMailsPerDay counts notification mail only: keep it below the mail provider's daily quota so activation, password-reset and address-change mail still go out (the default 100 leaves 200 of Brevo's free 300 a day); maxWatchesPerUser bounds each watch list. Every mail has a one-click unsubscribe.", + "_comment_notifications": "Optional, needs userManagement.enabled (docs/user-guide/accounts.md, Node notifications). Logged-in users watch nodes and get one mail per check when a watched node goes offline, comes back or reports a low battery; admins can also watch for new foreign nodes and observers going offline. Thresholds are healthThresholds and batteryThresholds. A check runs every intervalMinutes; at most perUserPerDay mails per user and maxMailsPerDay in total go out per 24 hours (over a limit the change is recorded and dropped, never queued). maxMailsPerDay counts notification mail only: keep it below the mail provider's daily quota so activation, password-reset and address-change mail still go out (the default 100 leaves 200 of Brevo's free 300 a day); maxWatchesPerUser bounds each watch list. Every mail has a one-click unsubscribe. Optional externalAlerts {url, maxAgeHours (48), label} offers the node.external event, fed by a JSON alerts feed computed outside CoreScope (docs/user-guide/accounts.md, External node alerts).", "_comment_usersBackup": "Part of userManagement (docs/user-guide/accounts.md, Backups). With accounts on, the server snapshots users.db at startup when the newest snapshot is older than 24 hours, then about every 24 hours, to users-.db (UTC, mode 0600) in dir (empty: backups/ next to users.db), and deletes the oldest beyond keep (default 7), never the one just written. On unless enabled is false. Snapshots hold password hashes, and deleted accounts stay in them for up to keep days: protect the directory like users.db. A dir that already exists is not tightened to 0700: set that yourself. Admins download a fresh snapshot at /api/admin/users-backup. A restore brings back accounts deleted after the snapshot (also self-deletions), old passwords, revoked sessions and used links: follow the Restore steps in the doc (note the deletions from the current audit log first, then disable those accounts and clear sessions and tokens before starting, and delete them again in the admin area).", "customizer": { "disabledTabs": [], diff --git a/docs/api-spec.md b/docs/api-spec.md index 3a553748c..92b2614ca 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -50,8 +50,15 @@ - [GET /api/traces/:hash](#get-apitraceshash) - [GET /api/config/theme](#get-apiconfigtheme) - [GET /api/config/regions](#get-apiconfigregions) +- [GET /api/config/region-quick-picks](#get-apiconfigregion-quick-picks) - [GET /api/config/areas](#get-apiconfigareas) - [GET /api/config/areas/polygons](#get-apiconfigareaspolygons) +- [GET /api/config/areas/geojson](#get-apiconfigareasgeojson) +- [GET /api/data/config](#get-apidataconfig) +- [GET /api/data/summary](#get-apidatasummary) +- [GET /api/data/cube](#get-apidatacube) +- [GET /api/data/packets](#get-apidatapackets) +- [GET /api/data/dashboards](#get-apidatadashboards) - [GET /api/config/client](#get-apiconfigclient) - [GET /api/config/cache](#get-apiconfigcache) - [GET /api/config/map](#get-apiconfigmap) @@ -1890,9 +1897,11 @@ not being the same as "declared nothing"), which apply here identically. ### Query Parameters -| Param | Type | Default | Description | -|----------|--------|---------|---------------------------------| -| `window` | string | `24h` | Time window: `1h`, `24h`, `7d` | +| Param | Type | Default | Description | +|----------|--------|------------|---------------------------------| +| `window` | string | `24h` | Time window: `1h`, `24h`, `7d` | +| `mode` | string | `declared` | `declared` (this section) or `transport` (see [Transport view](#transport-view-modetransport)) | +| `scope` | string | — | `mode=transport` only: region scope to split the fleet by (`be`, `be-van`), with or without `#`, any case | ### Response `200` @@ -1932,6 +1941,12 @@ not being the same as "declared nothing"), which apply here identically. { "error": "window must be 1h, 24h, or 7d" } ``` +or, for an unknown `mode`: + +```json +{ "error": "mode must be declared or transport" } +``` + **Notes:** - Only repeaters with **at least one** declared-regions answer appear in `repeaters`. A repeater that was never successfully asked is absent, not shown as a row that declares @@ -2038,6 +2053,52 @@ not being the same as "declared nothing"), which apply here identically. --- + +### Transport view (`mode=transport`) + +Issue #2142. One row per repeater **seen forwarding** in the window, whether or not it has +ever answered a declared-regions request. Built from the same single forwarding scan as the +declared view, with the same attribution rules (FLOOD-family route types only, no 1-byte +hops, a hop whose prefix matches several repeaters is credited to none of them), but with +every repeater and room this instance knows as a target instead of only the declared ones. +"Transported" means **seen carrying**, not configured for; the declared side is reported +separately where it exists. Cached per window with the same TTLs as the declared view; the +`scope` filter is applied to the cached result. + +```jsonc +{ + "mode": "transport", + "window": string, + "since": string (ISO), + "scope": string | undefined, // normalised ?scope= filter ("#FR" -> "fr"); present only when given + "carrying": number | undefined, // rows with carriesScope: true; only with scope + "notCarrying": number | undefined, // rows with carriesScope: false; only with scope + "repeaters": [ + { + "publicKey": string, + "name": string | null, // null = no nodes row for this key + "role": string | null, + "transported": [ // named region scopes seen forwarded, most packets first + { "scope": string, "packets": number, "firstSeen": string (ISO), "lastSeen": string (ISO) } + ], + "unscopedPackets": number, // plain floods forwarded + "unmatchedPackets": number, // scoped packets whose region this instance holds no key for + "ambiguousHops": number, // hops shared with another repeater's prefix, credited to neither + "asked": boolean, // a declared-regions answer exists + "declaredRegions": [string] | null,// null when not asked; [] when it answered with no named region + "declaredWildcard": boolean, + "configState": string | undefined, // as in the declared view; only when asked + "declaredAt": string | undefined, // only when asked + "notObserved": [string] | null, // declared regions not seen carried; null when not asked + "carriesScope": boolean | undefined // only with scope + } + ] +} +``` + +A repeater with no attributed forwarding in the window (only ambiguous hops, or no traffic) +is not listed. Rows are sorted by name, then public key. + ## GET /api/scope-stats Scope-based packet statistics over a time window. Requires ingestor `scope_name_v1` migration to have run. @@ -2250,24 +2311,50 @@ Returns a flat key-value object. --- +## GET /api/config/region-quick-picks + +Named groups of region codes from `config.json` `regionQuickPicks`, offered as one-tap choices by +the region filter. Names and codes are trimmed, codes upper-cased and de-duplicated in their +configured order, groups without a name or any code dropped; at most 20 groups of 200 codes. + +### Response `200` + +```jsonc +{ + "quickPicks": [ + { + "name": string, // button label + "description": string | undefined, // tooltip + "regions": [string] // IATA codes, as configured (may include codes with no observer yet) + } + ] +} +``` + +`quickPicks` is `[]` when none are configured. The client offers a group only when at least one +of its codes appears in `GET /api/config/regions`, and selects just those codes. + +--- + ## GET /api/config/areas -Available area filters defined in `config.json` under `areas`. Used by the frontend to populate the area pill bar. Entries with an empty `label` (e.g. comment keys) are excluded. +Available area filters: those defined in `config.json` under `areas`, then those in the GeoJSON file named by `areasFile`, in the file's order. Used by the frontend to populate the area pill bar. Entries with an empty `label` (e.g. comment keys) are excluded. ### Response `200` ```jsonc [ { - "key": string, // area key as defined in config (e.g. "bayarea") - "label": string // display name (e.g. "Bay Area") + "key": string, // area key as defined in config (e.g. "bayarea"), or a feature's code in areasFile + "label": string, // display name (e.g. "Bay Area") + "layer": string // "region" for config.json areas; the feature's layer for areasFile areas } ] ``` Returns `[]` when no areas are configured. -**Note:** Polygon coordinates are **not** included. Use `/api/config/areas/polygons` for the full geometry. +**Note:** Polygon coordinates are **not** included. Use `/api/config/areas/geojson` for every area's shape (config.json and `areasFile` alike), or `/api/config/areas/polygons` for config.json's raw entries. --- @@ -2295,6 +2382,195 @@ Returns `[]` when no areas are configured. --- +## GET /api/config/areas/geojson + +Every area's shape, for drawing on a map: config.json's polygons and boxes and the features of `areasFile`, as one GeoJSON FeatureCollection. Rings are simplified to about 450 m (never dropping an area or opening a ring) and the response is built once per layer. + +### Query + +| Param | Description | +|---|---| +| `layer` | Only this layer's areas. Omitted: every layer. | + +### Response `200` + +```jsonc +{ + "type": "FeatureCollection", + "features": [{ + "type": "Feature", + "properties": { "code": string, "label": string, "layer": string }, + "geometry": { "type": "MultiPolygon", "coordinates": [[[[lon, lat]]]] } // GeoJSON [lon, lat] order + }] +} +``` + +`features` is `[]` when no areas are configured. + +--- + +## GET /api/data/config + +The Data tab's set-up. The tab is off unless `data.enabled` is set in `config.json`. Areas (`areasFile` or `areas`) are optional: without them `places` is false, nothing is placed (every packet starts and is heard in `unknown`), and the place dimensions are left out of `dimensions`. + +### Response `200` + +```jsonc +{ + "enabled": boolean, // false: nothing else is sent and the other /api/data routes answer 404 + "places": boolean, // false when no areas are defined: layer, layers, home and areas are omitted + "layer": string, // the areas layer packets are placed in + "layers": [string], + "home": string, // data.homeArea, or omitted + "areas": [{ "code": string, "label": string }], // in the file's order + "windows": [{ "key": "24h" | "7d" | "30d", "label": string }], // those data.days reaches + "groups": [{ "key": string, "label": string, "types": [number], "floodOnly": boolean }], + "typeNames": { "": string }, + "dimensions": [string], // filter dimensions that mean something here; without areas, not border, origin, heard, through or how + "days": number, + "rows": number, // rows held: one per packet per receiving area + "coveredFrom": string, // ISO time the index holds every packet from + "filling": boolean // true while the startup fill runs +} +``` + +--- + +## GET /api/data/summary + +One period's headline figures. Cached 60 s. + +| Param | Description | +|---|---| +| `window` | `24h`, `7d` or `30d`, as far as `data.days` reaches (400 otherwise) | + +### Response `200` + +```jsonc +{ + "window": string, "label": string, "from": string, "to": string, + "coveredFrom": string, "complete": boolean, // complete: the index covers the whole period + "bucketSeconds": number, + "packets": number, // distinct packets + "crossBorder": number, // packets heard in an area other than the one they started in + "bases": { "advert" | "node" | "first-relay" | "zero-hop" | "unknown": number }, // how starts were decided + "areas": [{ "code": string, "observed": boolean, "originated": number }], + "matrix": [{ "origin": string, "heard": string, "packets": number, "relayed": number, "across": number }], + "matrixByGroup": { "": [ /* cells as matrix */ ] }, + "flows": [{ + "origin": string, "heard": string, "packets": number, "relayed": number, "across": number, + "viaHome": number, // a home repeater passed it on + "from": [{ "key": string, "name": string, "area": string, "packets": number }], // relays heard from + "gates": [ /* as from: home relays at the boundary */ ] + }] +} +``` + +A packet's start (`origin`) is, first rule that answers: its advert's own GPS; for an advert without one, the sender's node record; the first repeater to pass it on, when its hop is 2 bytes or more (a shorter prefix shared by several repeaters places it only when they all stand in one area); the area of an observer that heard it with no repeater; otherwise `unknown`. `relayed` counts packets an area's own repeater carried in; `across` those heard straight from the start area. + +--- + +## GET /api/data/cube + +Packets per time bucket along every dimension the tab can filter or split by. Cached 60 s. + +| Param | Description | +|---|---| +| `window` | as `/api/data/summary` | + +### Response `200` + +```jsonc +{ + "window": string, "from": string, "to": string, "coveredFrom": string, "complete": boolean, + "bucketSeconds": number, // 600 for 24h, 3600 for 7d, 21600 for 30d + "buckets": [number], // bucket start times, unix seconds + "origins": [string], "heard": [string], // area codes, "unknown" last + "types": [number], "routes": [number], + "scopes": [{ "key": string, "class": "direct" | "unscoped" | "unrecognised" | "scoped" }], + "how": ["relayed", "across", "unclear"], + "through": [string], // "" for none, else area codes joined with "+" + "channels": [string], // channel name, "hash:XX" when no key is held, "" for non-channel traffic + "rows": [[bucket, origin, heard, type, scope, how, route, through, channel, packets]] // indexes into the lists +} +``` + +--- + +## GET /api/data/packets + +The packets behind any figure, under the same filters. Newest first, at most 2,000 rows, with the full total. Two run at a time. + +| Param | Description | +|---|---| +| `window` | as `/api/data/summary` | +| `from`, `to` | optional unix seconds, `[from, to)` | +| `f` | optional JSON list of filters: `{"d": dimension, "v": [values], "n": 1 to exclude, "x": 1 for an exact "through" match}`. Dimensions: `border` (local, crossed, unknown), `origin`, `heard`, `through` (area codes, or `straight`), `kind` (a group key, or `direct-advert`), `type`, `channel`, `scope`, `sclass`, `how`, `routing` (flood, direct). 400 on bad JSON or an unknown dimension. | + +### Response `200` + +```jsonc +{ + "total": number, "limit": 2000, + "rows": [{ + "hash": string, "at": number, "type": number, "typeName": string, "kind": string, "routing": string, + "scope": string, "scopeClass": string, "channel": string, "border": string, + "origin": string, "basis": string, "heard": string, "through": string, "how": string, "observers": number, + "heardFrom": string, "heardFromIn": string, // the relay observers there heard it from, and its area + "boundary": string, "boundaryIn": string // the home relay at the boundary (with data.homeArea) + }] +} +``` + +--- + +## GET /api/data/dashboards + +The dashboards the Data tab offers, in this order: + +1. the built-in ones (generic; without areas, a set that leaves out the place views); +2. the operator's, from the file named by `data.dashboardsFile`. + +All are validated at startup. Without areas, an operator dashboard with an `area` variable or a place dimension (`border`, `origin`, `heard`, `through`, `how`) stops startup with the reason. A visitor's own dashboards live in their browser and are never sent here. + +### Response `200` + +```jsonc +{ + "default": string, // id of the dashboard to open first (data.defaultDashboard, else the first built-in) + "home": string, // data.homeArea, the default of a $home variable; omitted when unset + "dashboards": [{ + "schema": 1, + "id": string, // lower-case letters, digits and dashes + "title": string, + "description": string, + "window": "24h" | "7d" | "30d", + "source": "built-in" | "operator", + "variables": [{ "name": string, "kind": "area" | "scope" | "channel" | "text", "label": string, "default": string }], + "panels": [{ + "id": string, + "title": string, // may contain $variables + "type": "bar" | "line" | "area" | "matrix" | "stat" | "table" | "top" | "text", + "query": { + "window": string, // overrides the dashboard period for this panel + "filters": [ /* as /api/data/packets f=; values may be $variables */ ], + "x": "time" | dimension, "split": dimension, "facet": dimension, + "mode": "count" | "share", "rollup": "10m" | "30m" | "1h" | "6h" | "1d" | "1w", + "pick": [string], // series shown on their own; the rest are counted together + "rows": dimension, "cols": dimension, // matrix + "dim": dimension, "top": number // top list + }, + "options": { "text": string }, // text panels: short Markdown + "layout": { "x": number, "y": number, "w": number, "h": number } // 12-column grid + }] + }] +} +``` + +`404` when the tab is off. The file is a JSON list of these documents, exactly as the tab's **Export** saves them; a file with an unknown field, panel type or dimension, or more than 50 dashboards or 24 panels, stops startup with the reason. + +--- + ## GET /api/config/client Client-side configuration values. diff --git a/docs/examples/areas.example.geojson b/docs/examples/areas.example.geojson new file mode 100644 index 000000000..2512e0aaf --- /dev/null +++ b/docs/examples/areas.example.geojson @@ -0,0 +1,23 @@ +{ + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": { "code": "BAY", "label": "Bay Area", "layer": "region", "iata": ["SJC", "SFO", "OAK"] }, + "geometry": { + "type": "Polygon", + "coordinates": [[[-122.55, 37.90], [-121.75, 37.90], [-121.75, 37.25], [-122.55, 37.25], [-122.55, 37.90]]] + } + }, + { + "type": "Feature", + "properties": { "code": "MRY", "label": "Monterey Bay", "layer": "region", "iata": ["MRY"] }, + "geometry": { + "type": "MultiPolygon", + "coordinates": [ + [[[-122.05, 37.05], [-121.60, 37.05], [-121.60, 36.45], [-122.05, 36.45], [-122.05, 37.05]]] + ] + } + } + ] +} diff --git a/docs/user-guide/accounts.md b/docs/user-guide/accounts.md index 5da34714f..65e04bd0a 100644 --- a/docs/user-guide/accounts.md +++ b/docs/user-guide/accounts.md @@ -189,6 +189,38 @@ watched node changes state. Admins can also watch the instance. turns them back on. - Watch lists are private: admins see counts on the overview, not lists. +#### External node alerts (optional) + +A job outside CoreScope can publish alerts about nodes, for example coverage sectors +where a repeater is never heard by passing cars (#2177). With `externalAlerts` set, +users can choose the event *A watched node gets a