Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions db/observers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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})
}
Expand Down
24 changes: 24 additions & 0 deletions db/observers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
11 changes: 11 additions & 0 deletions db/polling_foreign_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,11 @@ func TestNodePollerForeignPostgres(t *testing.T) {
w.reading(local, tg, 2)

foreignNode, localNode := nodeOf(foreign), nodeOf(local)
for _, key := range [][]byte{foreign.pub, local.pub} {
if observer, poller := s.AdvertRoles(ctx, key); !observer || !poller {
t.Errorf("advert must recognize a foreign claim or recent readings: observer=%t poller=%t", observer, poller)
}
}
// The node flags: a foreign claim makes a poller, marked foreign; readings alone make a local one.
if n, err := s.GetNode(ctx, foreignNode); err != nil || !n.IsPoller || !n.IsForeignPoller || n.IsLocalPoller {
t.Fatalf("foreign node flags: %+v %v", n, err)
Expand All @@ -294,6 +299,12 @@ func TestNodePollerForeignPostgres(t *testing.T) {
if err != nil || p.Claim != nil || p.Readings24h != 1 || p.ForeignReadings24h != 1 || len(p.Targets) != 1 {
t.Fatalf("reading-only: %+v %v", p, err)
}
if _, err := pool.Exec(ctx, `UPDATE repeater_readings SET received_at = now() - interval '25 hours' WHERE observer_public_key=$1`, local.pub); err != nil {
t.Fatal(err)
}
if observer, poller := s.AdvertRoles(ctx, local.pub); !observer || poller {
t.Errorf("expired readings must not mark an observer as a poller: observer=%t poller=%t", observer, poller)
}
}

func TestNodePollerLocalPostgres(t *testing.T) {
Expand Down
6 changes: 6 additions & 0 deletions db/queries/polling.sql
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,12 @@ SELECT (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = $1)
OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = $1)
OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = $1 AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean;

-- name: GetAdvertRoles :one
SELECT EXISTS (SELECT 1 FROM observers WHERE public_key = @public_key::bytea) AS is_observer,
(EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = @public_key::bytea)
OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = @public_key::bytea)
OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = @public_key::bytea AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_poller;

-- name: DeletePollingCandidates :exec
DELETE FROM polling_candidates WHERE observer_public_key = $1;

Expand Down
15 changes: 15 additions & 0 deletions db/sqlc/mock/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions db/sqlc/polling.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions db/sqlc/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 2 additions & 4 deletions internal/ingest/ingest.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,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 polls: it has a polling claim or sent readings without one.
IsPollerByPubkey(ctx context.Context, pubkey []byte) bool
// AdvertRoles reports observer and poller status for the advertised key in one snapshot.
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)
Expand Down
10 changes: 7 additions & 3 deletions internal/ingest/ingest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -255,8 +257,10 @@ func (s *stubDB) InsertObserverTelemetry(_ context.Context, _ uuid.UUID, reporte
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
}
Expand Down
3 changes: 1 addition & 2 deletions internal/ingest/side_effects.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 8 additions & 5 deletions internal/ingest/side_effects_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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():
Expand Down
Loading