diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index c020c1000..c85340853 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -688,6 +688,7 @@ 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-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/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/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..af4477a49 100644 --- a/cmd/server/config.go +++ b/cmd/server/config.go @@ -104,6 +104,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"` @@ -876,6 +881,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/db.go b/cmd/server/db.go index b396a266d..79d1e7d2b 100644 --- a/cmd/server/db.go +++ b/cmd/server/db.go @@ -3223,6 +3223,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 +3298,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/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/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..f645ecaf7 100644 --- a/cmd/server/openapi.go +++ b/cmd/server/openapi.go @@ -41,12 +41,13 @@ 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/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 +104,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}, @@ -169,6 +170,9 @@ func routeDescriptions() map[string]routeMeta { "GET /api/scope-audit": {Summary: "Network-wide scope audit", Description: "For every repeater that has answered a declared-regions request: the regions it declares, which of those it has NOT been observed forwarding in the window, which scopes it forwards without declaring, and whether it forwards unscoped floods while omitting the '*' wildcard. '*' is never listed as a region — it governs unscoped floods, not a scope. Repeaters never successfully asked are absent rather than shown as declaring nothing. Rows with missing regions sort first; a short window is weak evidence, since a quiet region simply has no traffic.", Tag: "analytics", QueryParams: []paramMeta{ {Name: "window", Description: "Time window: 1h, 24h, or 7d (default 24h)", Type: "string"}, + {Name: "mode", Description: "declared (default) or transport", Type: "string"}, + {Name: "scope", Description: "mode=transport only: region scope to split the fleet by", Type: "string"}, + {Name: "region", Description: "Observer IATA codes, comma-separated: count only forwarding heard by observers there. All means no filter", Type: "string"}, }}, // Analytics 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..62a290c74 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -68,6 +68,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 +101,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 +233,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,6 +273,7 @@ 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") @@ -592,6 +610,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(".") @@ -1420,7 +1447,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 +1558,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 @@ -1618,7 +1737,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 +3305,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..cf6cb6160 100644 --- a/cmd/server/scope_audit.go +++ b/cmd/server/scope_audit.go @@ -393,6 +393,51 @@ var scopeAuditForwarderScanQuery = ` AND LENGTH(je.value) >= ` + fmt.Sprint(minForwarderHopHexLen) + ` ` +// observerRegionClause returns the condition that limits a query over +// observations aliased o to those heard by observers in codes, with its +// arguments. No codes means no condition. Codes that resolve to no observer +// match nothing, rather than silently widening to every observer. +func (db *DB) observerRegionClause(q interface { + Query(string, ...interface{}) (*sql.Rows, error) +}, codes []string) (string, []interface{}, error) { + if len(codes) == 0 { + return "", nil, nil + } + col, obsCol := "o.observer_id", "id" + if db.isV3 { + col, obsCol = "o.observer_idx", "rowid" + } + placeholders := strings.TrimSuffix(strings.Repeat("?,", len(codes)), ",") + args := make([]interface{}, len(codes)) + for i, c := range codes { + args[i] = c + } + rows, err := q.Query("SELECT "+obsCol+" FROM observers WHERE UPPER(TRIM(iata)) IN ("+placeholders+")", args...) + if err != nil { + return "", nil, err + } + defer rows.Close() + var ids []interface{} + for rows.Next() { + var id interface{} + if err := rows.Scan(&id); err != nil { + return "", nil, err + } + ids = append(ids, id) + } + if err := rows.Err(); err != nil { + return "", nil, err + } + if len(ids) == 0 { + return " AND 0", nil, nil + } + // The unary + keeps SQLite off the observer index. Driven from it, the + // scan reads every observation the region's observers ever made and checks + // the window per row (13.4s for one region over 24h on a live-shaped database); + // driven from the first_seen window like the unfiltered scan, 0.25s. + return " AND +" + col + " IN (" + strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",") + ")", ids, nil +} + // scopeAuditWindowMetaQuery reads the two per-TRANSMISSION facts the hop scan // used to carry on every hop row: the scope name and the timestamp. It applies // the identical window and route-type filter, so it covers every transmission @@ -567,6 +612,15 @@ type scopeAuditSeenKey struct { // same target; TestScopeAuditForwardingCountsOneTransmissionOncePerTarget pins // it. func (s *PacketStore) ScopeAuditForwarding(sinceISO string, targets []string) (map[string]*scopeAuditTargetAgg, error) { + return s.ScopeAuditForwardingHeardIn(sinceISO, targets, nil) +} + +// ScopeAuditForwardingHeardIn is ScopeAuditForwarding restricted to hops heard +// by observers in the given IATA regions (normalised codes; nil means every +// observer). The regions are resolved to their observers first and the scan +// filters on the observation's own observer column, so the hop scan never +// joins the observers table. +func (s *PacketStore) ScopeAuditForwardingHeardIn(sinceISO string, targets []string, regionCodes []string) (map[string]*scopeAuditTargetAgg, error) { byLen := scopeAuditPrefixIndex(targets) result := make(map[string]*scopeAuditTargetAgg, len(targets)) @@ -586,7 +640,11 @@ func (s *PacketStore) ScopeAuditForwarding(sinceISO string, targets []string) (m return nil, err } - rows, err := tx.Query(scopeAuditForwarderScanQuery, sinceISO) + observerClause, observerArgs, err := s.db.observerRegionClause(tx, regionCodes) + if err != nil { + return nil, fmt.Errorf("scope audit region observers: %w", err) + } + rows, err := tx.Query(scopeAuditForwarderScanQuery+observerClause, append([]interface{}{sinceISO}, observerArgs...)...) if err != nil { return nil, fmt.Errorf("scope audit forwarder scan: %w", err) } @@ -845,10 +903,56 @@ type ScopeAuditRow struct { // (see AllCurrentDeclaredRegions). type ScopeAuditResponse struct { Window string `json:"window"` - Since string `json:"since"` // ISO — start of the observed-forwarding window + Since string `json:"since"` // ISO — start of the observed-forwarding window + Region string `json:"region,omitempty"` // observer IATA filter, normalised, when given 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"` + Region string `json:"region,omitempty"` // observer IATA filter, normalised, when given + 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 @@ -997,8 +1101,23 @@ func (s *Server) handleScopeAudit(w http.ResponseWriter, r *http.Request) { } sinceISO := time.Now().Add(-lookback).UTC().Format(time.RFC3339) + // ?region= is the observer IATA filter, as on every other endpoint: count + // only forwarding heard by observers there. + regionCodes := normalizeRegionCodes(r.URL.Query().Get("region")) + region := strings.Join(regionCodes, ",") + + switch r.URL.Query().Get("mode") { + case "", "declared": + case "transport": + s.serveScopeTransport(w, r, window, region, sinceISO) + return + default: + writeError(w, 400, "mode must be declared or transport") + return + } - if cached, ok := s.scopeAuditCached(window); ok { + key := window + "|" + region + if cached, ok := s.scopeAuditCached(window, key); ok { writeJSON(w, cached) return } @@ -1009,18 +1128,18 @@ func (s *Server) handleScopeAudit(w http.ResponseWriter, r *http.Request) { // millions of rows, which is the shape that turns a thundering herd from // wasteful into expensive. Same treatment /api/observers and // /api/nodes/{pubkey}/reach already have. - v, err, _ := s.scopeAuditSF.Do(window, func() (interface{}, error) { + v, err, _ := s.scopeAuditSF.Do(key, func() (interface{}, error) { // Waiters that arrive while a scan is in flight are served by that // scan's result; this second look is for the caller that acquires the // group right after a winner stored one. - if cached, ok := s.scopeAuditCached(window); ok { + if cached, ok := s.scopeAuditCached(window, key); ok { return cached, nil } - resp, cErr := s.computeScopeAudit(window, sinceISO) + resp, cErr := s.computeScopeAudit(window, sinceISO, regionCodes) if cErr != nil { return nil, cErr } - s.scopeAuditStore(window, resp) + s.scopeAuditStore(key, resp) return resp, nil }) if err != nil { @@ -1047,37 +1166,37 @@ func scopeAuditTTLFor(window string) time.Duration { return 30 * time.Second } -// scopeAuditCached returns the cached response for a window while it is within -// that window's TTL. -func (s *Server) scopeAuditCached(window string) (*ScopeAuditResponse, bool) { +// scopeAuditCached returns the cached response under key (window|region) while +// it is within that window's TTL. +func (s *Server) scopeAuditCached(window, key string) (*ScopeAuditResponse, bool) { s.scopeAuditMu.Lock() defer s.scopeAuditMu.Unlock() if s.scopeAuditCache == nil { return nil, false } - cached, ok := s.scopeAuditCache[window] - if !ok || time.Since(s.scopeAuditCachedAt[window]) >= scopeAuditTTLFor(window) { + cached, ok := s.scopeAuditCache[key] + if !ok || time.Since(s.scopeAuditCachedAt[key]) >= scopeAuditTTLFor(window) { return nil, false } return cached, true } -// scopeAuditStore publishes a freshly computed response for a window. -func (s *Server) scopeAuditStore(window string, resp *ScopeAuditResponse) { +// scopeAuditStore publishes a freshly computed response under key (window|region). +func (s *Server) scopeAuditStore(key string, resp *ScopeAuditResponse) { s.scopeAuditMu.Lock() defer s.scopeAuditMu.Unlock() if s.scopeAuditCache == nil { s.scopeAuditCache = make(map[string]*ScopeAuditResponse) s.scopeAuditCachedAt = make(map[string]time.Time) } - s.scopeAuditCache[window] = resp - s.scopeAuditCachedAt[window] = time.Now() + s.scopeAuditCache[key] = resp + s.scopeAuditCachedAt[key] = time.Now() } // computeScopeAudit builds one window's audit response: the declared lists and // the forwarding evidence attributed to them. Split out of the handler so the // cache and its singleflight wrap a plain function instead of a request. -func (s *Server) computeScopeAudit(window, sinceISO string) (*ScopeAuditResponse, error) { +func (s *Server) computeScopeAudit(window, sinceISO string, regionCodes []string) (*ScopeAuditResponse, error) { declared, err := s.db.AllCurrentDeclaredRegions() if err != nil { return nil, err @@ -1090,7 +1209,7 @@ func (s *Server) computeScopeAudit(window, sinceISO string) (*ScopeAuditResponse forwarding := map[string]*scopeAuditTargetAgg{} if s.store != nil { - forwarding, err = s.store.ScopeAuditForwarding(sinceISO, targets) + forwarding, err = s.store.ScopeAuditForwardingHeardIn(sinceISO, targets, regionCodes) if err != nil { return nil, err } @@ -1125,7 +1244,7 @@ func (s *Server) computeScopeAudit(window, sinceISO string) (*ScopeAuditResponse identities := s.db.scopeAuditNodeIdentities(targets) - resp := &ScopeAuditResponse{Window: window, Since: sinceISO, Repeaters: []ScopeAuditRow{}} + resp := &ScopeAuditResponse{Window: window, Since: sinceISO, Region: strings.Join(regionCodes, ","), Repeaters: []ScopeAuditRow{}} for _, d := range declared { pk := strings.ToLower(d.Target) if s.cfg != nil && s.cfg.IsBlacklisted(pk) { @@ -1259,3 +1378,238 @@ 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, region, sinceISO string) { + key := window + "|" + region + resp, ok := s.scopeTransportCached(window, key) + if !ok { + v, err, _ := s.scopeAuditSF.Do("transport|"+key, func() (interface{}, error) { + if cached, ok := s.scopeTransportCached(window, key); ok { + return cached, nil + } + fresh, cErr := s.computeScopeTransport(window, sinceISO, normalizeRegionCodes(region)) + if cErr != nil { + return nil, cErr + } + s.scopeTransportStore(key, 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, key string) (*ScopeTransportResponse, bool) { + s.scopeAuditMu.Lock() + defer s.scopeAuditMu.Unlock() + cached, ok := s.scopeTransportCache[key] + if !ok || time.Since(s.scopeTransportCachedAt[key]) >= scopeAuditTTLFor(window) { + return nil, false + } + return cached, true +} + +func (s *Server) scopeTransportStore(key 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[key] = resp + s.scopeTransportCachedAt[key] = 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, regionCodes []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.ScopeAuditForwardingHeardIn(sinceISO, targets, regionCodes) + 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, Region: strings.Join(regionCodes, ","), 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_audit_region_test.go b/cmd/server/scope_audit_region_test.go new file mode 100644 index 000000000..80bc09d92 --- /dev/null +++ b/cmd/server/scope_audit_region_test.go @@ -0,0 +1,224 @@ +package main + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/gorilla/mux" +) + +// The Scope Audit had no region selector, unlike every other page. With +// ?region= both views count only forwarding heard by observers in +// those regions: "as heard by", the same meaning region= has on /api/nodes +// and /api/packets, not "located in". + +// setupScopeRegionServer is setupScopeAuditServer with observers and the v3 +// observations.observer_idx column, so a hop can be attributed to the +// observer that heard it. +func setupScopeRegionServer(t *testing.T) (*Server, *mux.Router) { + t.Helper() + srv, router := setupScopeAuditServer(t) + for _, ddl := range []string{ + `CREATE TABLE observers (id TEXT, name TEXT, iata TEXT)`, + `ALTER TABLE observations ADD COLUMN observer_idx INTEGER`, + `INSERT INTO observers (rowid, id, name, iata) VALUES (1, 'obs-sfo', 'San Francisco', 'SFO'), (2, 'obs-bru', 'Brussels', 'BRU')`, + } { + if _, err := srv.db.conn.Exec(ddl); err != nil { + t.Fatal(err) + } + } + if err := srv.db.detectSchema(context.Background(), srv.db.conn); err != nil { + t.Fatal(err) + } + if !srv.db.isV3 { + t.Fatal("fixture must be v3 (observer_idx) or the test exercises nothing") + } + return srv, router +} + +var heardCounter int + +// seedHeard inserts one flood transmission forwarded by hop, heard by the +// observer with the given rowid. +func seedHeard(t *testing.T, srv *Server, hop string, seed scopeSeed, observerRowid int) { + t.Helper() + heardCounter++ + res, err := srv.db.conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type, code1, code2, scope_name) + VALUES ('AA', ?, ?, ?, 1, ?, '00', ?)`, fmt.Sprintf("heard%d", heardCounter), + time.Now().UTC().Add(-time.Minute).Format(time.RFC3339), RouteFlood, seed.code1, seed.scopeName) + if err != nil { + t.Fatal(err) + } + id, _ := res.LastInsertId() + path := fmt.Sprintf(`["%s"]`, strings.ToUpper(hop)) + if observerRowid == 0 { // v2 fixture: the caller attributes observer_id itself + _, err = srv.db.conn.Exec(`INSERT INTO observations (transmission_id, path_json, timestamp) VALUES (?, ?, ?)`, id, path, time.Now().Unix()) + } else { + _, err = srv.db.conn.Exec(`INSERT INTO observations (transmission_id, path_json, timestamp, observer_idx) VALUES (?, ?, ?, ?)`, id, path, time.Now().Unix(), observerRowid) + } + if err != nil { + t.Fatal(err) + } +} + +// A declared "be", heard carrying #be by San Francisco and #de by Brussels. +func seedRegionalForwarding(t *testing.T, srv *Server) { + t.Helper() + insertDeclared(t, srv, testFullPubkeyA, time.Now().UTC().Format(time.RFC3339), "be", 0) + addRepeater(t, srv, testFullPubkeyA, "Alpha") + addRepeater(t, srv, testFullPubkeyB, "Bravo") + seedHeard(t, srv, testFullPubkeyA[:4], scopeMatched("#be"), 1) + seedHeard(t, srv, testFullPubkeyA[:4], scopeMatched("#de"), 2) + seedHeard(t, srv, testFullPubkeyB[:4], scopeMatched("#fr"), 2) +} + +func TestScopeAudit_RegionCountsOnlyHopsHeardThere(t *testing.T) { + srv, router := setupScopeRegionServer(t) + seedRegionalForwarding(t, srv) + + all := findScopeAuditRow(t, getScopeAudit(t, router, "").Repeaters, testFullPubkeyA) + if len(all.UndeclaredObserved) != 1 || all.UndeclaredObserved[0].Scope != "de" { + t.Fatalf("without a region, #de heard in Brussels should be undeclared-observed: %+v", all.UndeclaredObserved) + } + sfo := getScopeAudit(t, router, "?region=SFO") + row := findScopeAuditRow(t, sfo.Repeaters, testFullPubkeyA) + if len(row.UndeclaredObserved) != 0 { + t.Errorf("region=SFO must not count #de heard only in Brussels: %+v", row.UndeclaredObserved) + } + if len(row.NotObserved) != 0 { + t.Errorf("region=SFO: #be was heard in San Francisco, notObserved = %v", row.NotObserved) + } + if sfo.Region != "SFO" { + t.Errorf("region = %q, want the normalised codes echoed", sfo.Region) + } +} + +func TestScopeTransport_RegionListsOnlyRepeatersHeardThere(t *testing.T) { + srv, router := setupScopeRegionServer(t) + seedRegionalForwarding(t, srv) + got := getScopeTransport(t, router, "®ion=bru") + if got.Region != "BRU" { + t.Errorf("region = %q, want BRU", got.Region) + } + a := transportRow(t, got.Repeaters, testFullPubkeyA) + if len(a.Transported) != 1 || a.Transported[0].Scope != "de" { + t.Errorf("A as heard in Brussels: transported = %+v, want only de", a.Transported) + } + transportRow(t, got.Repeaters, testFullPubkeyB) + sfo := getScopeTransport(t, router, "®ion=SFO") + for _, r := range sfo.Repeaters { + if r.PublicKey == testFullPubkeyB { + t.Fatal("B was only heard in Brussels and must not be listed for region=SFO") + } + } +} + +func TestScopeAudit_RegionAllMeansNoFilter(t *testing.T) { + srv, router := setupScopeRegionServer(t) + seedRegionalForwarding(t, srv) + got := getScopeAudit(t, router, "?region=All") + row := findScopeAuditRow(t, got.Repeaters, testFullPubkeyA) + if len(row.UndeclaredObserved) != 1 || got.Region != "" { + t.Fatalf("region=All must behave like no region: undeclared=%+v region=%q", row.UndeclaredObserved, got.Region) + } +} + +func TestScopeAudit_RegionsAreCachedSeparately(t *testing.T) { + srv, router := setupScopeRegionServer(t) + seedRegionalForwarding(t, srv) + getScopeAudit(t, router, "?region=SFO") // fills the SFO entry first + row := findScopeAuditRow(t, getScopeAudit(t, router, "").Repeaters, testFullPubkeyA) + if len(row.UndeclaredObserved) != 1 { + t.Fatalf("the unfiltered view must not be served from the SFO cache entry: %+v", row.UndeclaredObserved) + } + tr := getScopeTransport(t, router, "®ion=SFO") + if len(transportRow(t, tr.Repeaters, testFullPubkeyA).Transported) != 1 { + t.Fatal("transport view for SFO should count only #be") + } +} + +func TestScopeAudit_RegionWithNoObserversMatchesNothing(t *testing.T) { + srv, router := setupScopeRegionServer(t) + seedRegionalForwarding(t, srv) + got := getScopeTransport(t, router, "®ion=ZZZ") + if len(got.Repeaters) != 0 { + t.Fatalf("a region with no observers must match no forwarding, got %d rows", len(got.Repeaters)) + } +} + +// On the v2 schema an observation names its observer by observers.id in +// observer_id rather than by rowid; the filter must follow it. +func TestScopeTransport_RegionOnV2Schema(t *testing.T) { + srv, router := setupScopeAuditServer(t) + for _, ddl := range []string{ + `CREATE TABLE observers (id TEXT, name TEXT, iata TEXT)`, + `ALTER TABLE observations ADD COLUMN observer_id TEXT`, + `INSERT INTO observers (id, name, iata) VALUES ('obs-sfo', 'San Francisco', 'SFO'), ('obs-bru', 'Brussels', 'BRU')`, + } { + if _, err := srv.db.conn.Exec(ddl); err != nil { + t.Fatal(err) + } + } + if err := srv.db.detectSchema(context.Background(), srv.db.conn); err != nil { + t.Fatal(err) + } + if srv.db.isV3 { + t.Fatal("fixture must be v2") + } + addRepeater(t, srv, testFullPubkeyA, "Alpha") + addRepeater(t, srv, testFullPubkeyB, "Bravo") + seedHeard(t, srv, testFullPubkeyA[:4], scopeMatched("#be"), 0) + seedHeard(t, srv, testFullPubkeyB[:4], scopeMatched("#fr"), 0) + if _, err := srv.db.conn.Exec(`UPDATE observations SET observer_id = CASE WHEN path_json LIKE ? THEN 'obs-sfo' ELSE 'obs-bru' END`, + `%`+strings.ToUpper(testFullPubkeyA[:4])+`%`); err != nil { + t.Fatal(err) + } + got := getScopeTransport(t, router, "®ion=SFO") + if len(got.Repeaters) != 1 || got.Repeaters[0].PublicKey != testFullPubkeyA { + t.Fatalf("v2 region=SFO should list only A, got %+v", got.Repeaters) + } +} + +// With an index on observations(observer_idx), as every real database has, +// SQLite drives "o.observer_idx IN (...)" from that index: every observation +// the region's observers ever made, then the window check per row. On a +// live-shaped database that was 13.4s for one region over 24h against 0.25s when +// the scan starts from the first_seen window as the unfiltered scan does. +func TestScopeAudit_RegionScanKeepsTheTimeIndex(t *testing.T) { + srv, _ := setupScopeRegionServer(t) + for _, ddl := range []string{ + `CREATE INDEX IF NOT EXISTS idx_transmissions_first_seen ON transmissions(first_seen)`, + `CREATE INDEX IF NOT EXISTS idx_observations_transmission_id ON observations(transmission_id)`, + `CREATE INDEX IF NOT EXISTS idx_observations_observer_idx ON observations(observer_idx)`, + } { + if _, err := srv.db.conn.Exec(ddl); err != nil { + t.Fatal(err) + } + } + clause, args, err := srv.db.observerRegionClause(srv.db.conn, []string{"SFO"}) + if err != nil || clause == "" { + t.Fatalf("clause=%q err=%v", clause, err) + } + rows, err := srv.db.conn.Query("EXPLAIN QUERY PLAN "+scopeAuditForwarderScanQuery+clause, + append([]interface{}{"2000-01-01T00:00:00Z"}, args...)...) + 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) + } + joined := strings.Join(plan, " | ") + if strings.Contains(joined, "idx_observations_observer_idx") || !strings.Contains(joined, "idx_transmissions_first_seen") { + t.Fatalf("the region scan must start from the first_seen window, not the observer index: %s", joined) + } +} 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..b37617954 --- /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, nil); 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..541147fb5 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) @@ -4256,16 +4257,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 +4269,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 +4287,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 +5155,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 +5414,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 +10306,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 +10512,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 +10573,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 +10600,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/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..cf951d6c0 100644 --- a/config.example.json +++ b/config.example.json @@ -404,6 +404,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 +469,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..452095f8d 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -50,6 +50,7 @@ - [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/client](#get-apiconfigclient) @@ -1890,9 +1891,12 @@ 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 | +| `region` | string | — | Observer IATA filter, comma-separated (`SFO,SJC`), both views: count only forwarding heard by observers in those regions. As on every other endpoint this means *heard by*, not *located in*; `All` means no filter, and codes with no observer match nothing. Each region set is cached separately | ### Response `200` @@ -1900,6 +1904,7 @@ not being the same as "declared nothing"), which apply here identically. { "window": string, // echoed window ("1h", "24h", or "7d") "since": string (ISO), // start of the observed-forwarding window + "region": string | undefined, // normalised ?region= codes ("sfo,sjc" -> "SFO,SJC"); present only when given "repeaters": [ { "publicKey": string, @@ -1932,6 +1937,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 +2049,53 @@ 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), + "region": string | undefined, // normalised ?region= codes; present only when given + "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,6 +2308,31 @@ 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. 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