From 7be0c820d91c49ae55785881fb0351f53beadcd7 Mon Sep 17 00:00:00 2001 From: n30nex Date: Thu, 26 Nov 2026 17:25:16 -0500 Subject: [PATCH] Read live advert roles in one database round trip --- db/observers.go | 9 +++++++++ db/observers_test.go | 24 ++++++++++++++++++++++++ db/queries/polling.sql | 4 ++++ db/sqlc/mock/querier.go | 15 +++++++++++++++ db/sqlc/polling.sql.go | 17 +++++++++++++++++ db/sqlc/querier.go | 1 + internal/ingest/ingest.go | 6 ++---- internal/ingest/ingest_test.go | 10 +++++++--- internal/ingest/side_effects.go | 3 +-- internal/ingest/side_effects_test.go | 13 ++++++++----- 10 files changed, 88 insertions(+), 14 deletions(-) diff --git a/db/observers.go b/db/observers.go index 418de872..ef49d4e3 100644 --- a/db/observers.go +++ b/db/observers.go @@ -617,6 +617,15 @@ func (s *Store) IsObserverByPubkey(ctx context.Context, pubkey []byte) bool { return err == nil } +// AdvertRoles reads both flags for a live node update in one database round trip. +func (s *Store) AdvertRoles(ctx context.Context, pubkey []byte) (isObserver, isPoller bool) { + roles, err := s.q.GetAdvertRoles(ctx, pubkey) + if err != nil { + return false, false + } + return roles.IsObserver, roles.IsPoller +} + func (s *Store) DeleteOldTelemetry(ctx context.Context, cutoff time.Time) error { return s.q.DeleteOldTelemetry(ctx, pgtype.Timestamptz{Time: cutoff, Valid: true}) } diff --git a/db/observers_test.go b/db/observers_test.go index 4a0c4423..beed059a 100644 --- a/db/observers_test.go +++ b/db/observers_test.go @@ -613,6 +613,30 @@ func TestGetObserverRadio_WithFields(t *testing.T) { } } +func TestAdvertRoles(t *testing.T) { + for _, tc := range []struct { + name string + row sqlc.GetAdvertRolesRow + err error + }{ + {"observer", sqlc.GetAdvertRolesRow{IsObserver: true}, nil}, + {"poller", sqlc.GetAdvertRolesRow{IsPoller: true}, nil}, + {"both", sqlc.GetAdvertRolesRow{IsObserver: true, IsPoller: true}, nil}, + {"neither", sqlc.GetAdvertRolesRow{}, nil}, + {"read error", sqlc.GetAdvertRolesRow{IsObserver: true}, errors.New("unavailable")}, + } { + t.Run(tc.name, func(t *testing.T) { + mock := mockdb.NewMockQuerier(gomock.NewController(t)) + key := []byte{1, 2} + mock.EXPECT().GetAdvertRoles(gomock.Any(), key).Return(tc.row, tc.err) + observer, poller := (&Store{q: mock}).AdvertRoles(context.Background(), key) + if observer != (tc.err == nil && tc.row.IsObserver) || poller != (tc.err == nil && tc.row.IsPoller) { + t.Fatalf("got observer=%t poller=%t", observer, poller) + } + }) + } +} + func TestIsObserverByPubkey_Found(t *testing.T) { ctrl := gomock.NewController(t) mock := mockdb.NewMockQuerier(ctrl) diff --git a/db/queries/polling.sql b/db/queries/polling.sql index 3132a81e..4f7b53e7 100644 --- a/db/queries/polling.sql +++ b/db/queries/polling.sql @@ -17,6 +17,10 @@ SELECT received_at FROM polling_claims WHERE observer_public_key = $1; -- name: IsPollerKey :one SELECT EXISTS (SELECT 1 FROM polling_claims WHERE observer_public_key = $1); +-- name: GetAdvertRoles :one +SELECT EXISTS (SELECT 1 FROM observers WHERE public_key = @public_key::bytea) AS is_observer, + EXISTS (SELECT 1 FROM polling_claims WHERE observer_public_key = @public_key::bytea) AS is_poller; + -- name: DeletePollingCandidates :exec DELETE FROM polling_candidates WHERE observer_public_key = $1; diff --git a/db/sqlc/mock/querier.go b/db/sqlc/mock/querier.go index 3e8dfb03..71ab2c78 100644 --- a/db/sqlc/mock/querier.go +++ b/db/sqlc/mock/querier.go @@ -1597,6 +1597,21 @@ func (mr *MockQuerierMockRecorder) GetAccount(ctx, id any) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccount", reflect.TypeOf((*MockQuerier)(nil).GetAccount), ctx, id) } +// GetAdvertRoles mocks base method. +func (m *MockQuerier) GetAdvertRoles(ctx context.Context, publicKey []byte) (db.GetAdvertRolesRow, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAdvertRoles", ctx, publicKey) + ret0, _ := ret[0].(db.GetAdvertRolesRow) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAdvertRoles indicates an expected call of GetAdvertRoles. +func (mr *MockQuerierMockRecorder) GetAdvertRoles(ctx, publicKey any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAdvertRoles", reflect.TypeOf((*MockQuerier)(nil).GetAdvertRoles), ctx, publicKey) +} + // GetAnalyticsRevision mocks base method. func (m *MockQuerier) GetAnalyticsRevision(ctx context.Context) (int64, error) { m.ctrl.T.Helper() diff --git a/db/sqlc/polling.sql.go b/db/sqlc/polling.sql.go index 567cf0dc..dfe54e08 100644 --- a/db/sqlc/polling.sql.go +++ b/db/sqlc/polling.sql.go @@ -175,6 +175,23 @@ func (q *Queries) DeletePollingCandidates(ctx context.Context, observerPublicKey return err } +const getAdvertRoles = `-- name: GetAdvertRoles :one +SELECT EXISTS (SELECT 1 FROM observers WHERE public_key = $1::bytea) AS is_observer, + EXISTS (SELECT 1 FROM polling_claims WHERE observer_public_key = $1::bytea) AS is_poller +` + +type GetAdvertRolesRow struct { + IsObserver bool `json:"is_observer"` + IsPoller bool `json:"is_poller"` +} + +func (q *Queries) GetAdvertRoles(ctx context.Context, publicKey []byte) (GetAdvertRolesRow, error) { + row := q.db.QueryRow(ctx, getAdvertRoles, publicKey) + var i GetAdvertRolesRow + err := row.Scan(&i.IsObserver, &i.IsPoller) + return i, err +} + const getPollingState = `-- name: GetPollingState :one SELECT paused, paused_until, excluded_nodes FROM polling_state WHERE id ` diff --git a/db/sqlc/querier.go b/db/sqlc/querier.go index 090caca2..d7047c44 100644 --- a/db/sqlc/querier.go +++ b/db/sqlc/querier.go @@ -215,6 +215,7 @@ type Querier interface { // Marks the hour complete and bumps the revision only when its content changed. FinishRollupHour(ctx context.Context, arg FinishRollupHourParams) (bool, error) GetAccount(ctx context.Context, id uuid.UUID) (Account, error) + GetAdvertRoles(ctx context.Context, publicKey []byte) (GetAdvertRolesRow, error) // Both counters only grow, so their sum changes whenever rolled content or coverage does. GetAnalyticsRevision(ctx context.Context) (int64, error) GetBackgroundState(ctx context.Context, key string) (json.RawMessage, error) diff --git a/internal/ingest/ingest.go b/internal/ingest/ingest.go index d19f32d2..3c383e02 100644 --- a/internal/ingest/ingest.go +++ b/internal/ingest/ingest.go @@ -153,10 +153,8 @@ type DB interface { // GetObserverRadio returns the current radio settings for the given observer. GetObserverRadio(ctx context.Context, observerID uuid.UUID) (RadioSettings, error) - // IsObserverByPubkey returns true if the given public key belongs to a known observer. - IsObserverByPubkey(ctx context.Context, pubkey []byte) bool - // IsPollerByPubkey returns true if the given public key has a polling claim. - IsPollerByPubkey(ctx context.Context, pubkey []byte) bool + // AdvertRoles reports observer registration and polling claim presence for the advertised key. + AdvertRoles(ctx context.Context, pubkey []byte) (isObserver, isPoller bool) // GetObserverScopes returns the list of scope names associated with the given observer. GetObserverScopes(ctx context.Context, observerID uuid.UUID) ([]string, error) diff --git a/internal/ingest/ingest_test.go b/internal/ingest/ingest_test.go index afe8a076..093a333f 100644 --- a/internal/ingest/ingest_test.go +++ b/internal/ingest/ingest_test.go @@ -148,7 +148,9 @@ type stubDB struct { upsertChannelIATACalls int traceHearings []TraceHearing packetIsNew bool - isPoller bool // returned by IsPollerByPubkey + isObserver bool + isPoller bool + advertRoleReads int observationInserted bool channelMessages []InsertChannelMessageParams observationCount int64 @@ -239,8 +241,10 @@ func (s *stubDB) InsertObserverTelemetry(_ context.Context, _ uuid.UUID, _ time. func (s *stubDB) GetObserverRadio(_ context.Context, _ uuid.UUID) (RadioSettings, error) { return RadioSettings{}, nil } -func (s *stubDB) IsObserverByPubkey(_ context.Context, _ []byte) bool { return false } -func (s *stubDB) IsPollerByPubkey(_ context.Context, _ []byte) bool { return s.isPoller } +func (s *stubDB) AdvertRoles(_ context.Context, _ []byte) (bool, bool) { + s.advertRoleReads++ + return s.isObserver, s.isPoller +} func (s *stubDB) GetObserverScopes(_ context.Context, _ uuid.UUID) ([]string, error) { return nil, nil } diff --git a/internal/ingest/side_effects.go b/internal/ingest/side_effects.go index 3531a871..d05c7a37 100644 --- a/internal/ingest/side_effects.go +++ b/internal/ingest/side_effects.go @@ -171,8 +171,7 @@ func (w *Worker) handlePayloadTypeSideEffects(ctx context.Context, packet *meshc w.log.Error(fmt.Sprintf("failed to upsert node short ID for %s", hex.EncodeToString(prefix4)), "error", err) } pubkeyHex := hex.EncodeToString(advert.PublicKey.PublicKeyBytes()) - isObserver := w.db.IsObserverByPubkey(ctx, advert.PublicKey.PublicKeyBytes()) - isPoller := w.db.IsPollerByPubkey(ctx, advert.PublicKey.PublicKeyBytes()) + isObserver, isPoller := w.db.AdvertRoles(ctx, advert.PublicKey.PublicKeyBytes()) var defaultScope *string if matchedScope != nil { defaultScope = matchedScope diff --git a/internal/ingest/side_effects_test.go b/internal/ingest/side_effects_test.go index 58b08a75..de739dba 100644 --- a/internal/ingest/side_effects_test.go +++ b/internal/ingest/side_effects_test.go @@ -334,16 +334,19 @@ func TestHandlePacket_Trace_RecordsTrace(t *testing.T) { } } -func TestAdvertNodeEventCarriesIsPoller(t *testing.T) { - for _, poller := range []bool{true, false} { +func TestAdvertNodeEventCarriesRoles(t *testing.T) { + for _, roles := range []struct{ observer, poller bool }{{}, {true, false}, {true, true}, {false, true}} { w, db := newTestWorker() - db.isPoller = poller + db.isObserver, db.isPoller = roles.observer, roles.poller go w.hub.Run() client := w.hub.NewClient() w.hub.AddScope(client, "poller", hub.Scope{Events: []hub.EventType{hub.EventNodeUpdate, hub.EventObserverStatus}}) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) waitForSummarySubscriber(t, ctx, w.hub, client) w.handlePayloadTypeSideEffects(ctx, buildAdvertPacket(t, false), "AAA", []byte{1}, RadioSettings{}, nil, nil, nil, snrTestValue(0), false, false) + if db.advertRoleReads != 1 { + t.Fatalf("expected one role lookup per advert, got %d", db.advertRoleReads) + } func() { for { select { @@ -355,8 +358,8 @@ func TestAdvertNodeEventCarriesIsPoller(t *testing.T) { if err := json.Unmarshal(event.Payload, &payload); err != nil { t.Fatal(err) } - if got, ok := payload["isPoller"]; !ok || got != poller { - t.Fatalf("isPoller = %v (present=%v), want %v: %s", got, ok, poller, event.Payload) + if payload["isObserver"] != roles.observer || payload["isPoller"] != roles.poller { + t.Fatalf("wrong advert roles for %+v: %s", roles, event.Payload) } return case <-ctx.Done():