diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cac178cc..d03ae461 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -69,7 +69,7 @@ jobs: - name: Verify stats and endpoint queries against PostgreSQL 16 env: BEACON_TEST_POSTGRES_DSN: postgres://postgres:backup-ci-only@127.0.0.1:5432/postgres?sslmode=disable - run: go test ./db -timeout 25m -run '^Test(Signal|Paths|PacketSummaries|PacketEndpointsResolveLive|ObserverMetrics|ObserverDirectoryLiveCountsMatchRaw|ObserverActivityLiveCountsMatchRaw|RouteEvidence|RouteEvidenceIndex|AnalyticsRetention|AnalyticsRetentionConcurrent|DeleteOldPacketsBatches|MeshMapperCatalogue|ChannelMessageScopes|NodeLocationReset|RunMigrations[A-Za-z]*|KnownRoutesIndexSet|PacketsDomainChecks|Reconfirm[A-Za-z]*|BigintCursors|RouteSearchHopOrder|StatsNodeTypesSplit|ListKnownRoutes|ListKnownRoutesMatchesLegacy|KnownRoutesCursorTies|KnownRoutesUnanalyzedRegion|KnownRoutesHopStatementsStayCustom|GlobalHopBranchesMatchToday|KnownRoutePaginationTies|KnownRoutesByIATAsMatchMerge|KnownRoutesByIATAsBounded|RouteRetentionCutoffsExact|DeleteExpiredRoutes|DeleteGraceRoutesSlice|GraceWatermarkHeldByLockedRow|OpenPoolsSettings|PlanRouterClassCUnnamed|PlanRouterParallelWorkers|APIStoreHopStatementsUnnamed|PgStatStatementsMigrationGuarded|DBStatements|DBStatementsNoExtension|PgStatStatementsMigrationNoCreatableSchema|IndexHealthBaselineOnReindex|UnusedIndexes|PgActivity|RollHourSetsWorkMem|RollupWritesKeyOrder|SmallTableIndexSet|NodeReadersAfterIndexDrops|ClockDriftWideValues|ObserverChannelReadersAfterIndexDrops|UpsertChannelWriteThrough|UpsertChannelHashOnlyWriteThrough|ChannelHashOnlyRehear|ReadOnlyPoolsRejectWrites|ListPacketsGlobalMatchesLegacy|PacketsGlobalCursorTies|ListPacketsWindowInvertedRows|PacketsLatestObserverTie|NodesLegacyCursorMatchesToday|NodesPageCursorTies|ListNodesSorted|ObserversLegacyCursorMatchesToday|ObserversNextCursorFromLastSeen|ObserverAdvertsPartialIndex|ObserverComparisonMatchesToday|AdvertsWaitForPayloadTypeBackfill|StatsProbeMatchesToday|TraceTagsKeysetMatchesToday|TelemetrySinceMatchesCatchAll|TraceTagPagination|TraceTagPaginationTies|TraceSummarySurvivesMissedHearing|CmiMigrationsIndexSet|InsertChannelMessageSeed[A-Za-z]*|AddChannelMessageIATA|CmiSeedAndAddRace|CmiInitAndBackfill|CmiMessageRangeReconcile|CmiObservationRangeReconcile|CmiBackfillRetries23503|WaitForPreBootWriters|ChannelMessagesByIATAsMatchesLegacy|ChannelMessagesZeroHitRegion|CmiTrustLifecycle|CmiFirstVerification|PacketSitesMigrationsIndexSet|InsertObservationMaintainsPacketSites|InsertObservationResendWritesNothing|PacketSitesRaceMaxMerge|InsertObservationSiteFallback|PacketSitesInitAndBackfill|FillPacketSitesSliceIdempotent|FillPacketSitesSliceRetries23503|PacketSitesReconcile|PacketSitesAudit|PacketSitesAuditTakesNewestHearing|PacketsBySitesMatchesTruth|PacketsBySitesCursorTies|PacketsBySitesManyBogusSites|PacketsBySitesSaturatedPagesFull|PacketsBySitesMatchesLegacy|PacketSitesTrustLifecycle|PacketsBySitesBounded|PacketsBySitesFallbackKeepsPageCursor|PacketsBySitesFarWindow|SweepPacketSitesFrontsPlan|IndexHealthPacketSitesFreshBaseline|PacketSitesFirstVerification|PacketSitesBackfillSlicesSparseIDs|PacketSitesBackfillResumesAcrossGaps|PacketSitesProgressCountsRows|PacketSitesAuditSamplesRows|PacketSitesVerifySamplesRows|PacedBackfillSlices|FillSessionsPlanCustom|FillAnalyzeFailureIsIgnored|FillAnalyzeOnlyNeverAnalyzed|HygieneIndexSet|HygieneReadersAfterIndexDrops|KnownRoutesColumns|SequenceUse|SequenceUseMixedCaseSchema|ObservationsIndexSet|ReadersAfterIndexDrops|PollingClaimReplaceIsSnapshot|PollingClaimOlderIsIgnored|PollingClaimLimits|PollingForeignClaims|PollingForeignClaimTwoRoutes|PollingForeignRequestNeedsAcknowledgement|NodePollerForeign|PollingForeignClaimedIsPerTarget|PollingForeignReadingNeedsApproval|PollingForeignRequestedAssignment|PollingForeignReadingNeverLatest|PollingDropUnplacedClaims|PacketBrokers|ObserverBrokersLastThirtyDays|PollingClaimTruncatesText|RepeaterReadingDedup|RepeaterReadingWithoutTagUsesSampledAt|PollingCandidatesEvidence|PollingAssignmentsOnePoller|PollingOwnerRowsLatestTs|CorroborateReadings|PollingLivenessUsesReceiveTime|PollingDeleteExpiredAndFlags|CorroborateReadingsUncountedFirst|CorroborateReadingsReachesEveryReading|ListPollingObservers|RepeaterReadingOutlivesObserver|RepeaterReadingTrustedAtInsert|RepeaterReadingTrustMigrationBackfill|PollingObserverIndexes|PollingElectionConcurrent|PollingOwnerRowsTrustedLatest|RepeaterReadingRateLimit|PollingClaimReceivedAt|PollingTargetsAdmin|PollingCandidatesEvidenceSince|PollingElectionLock|PollingEvidenceOutranksHealthyStranger|PollingApprovedAuthority|PollingClaimInterval|PollingClaimIntervalConcurrent|RepeaterReadingRateLimitConcurrent|RepeaterReadingObserverBudget|RepeaterReadingConstraints|RepeaterReadingWaitsForOpenInsert|PollingOrphanCleanupWaitsForElection|PollingLockKeys|NodeReadings|NodePolling|NodePoller|NodePollerReadIsOneSnapshot|ListLatestNodeReadings|UserCreateAndLookup|UserDuplicates|UserTokenConsume|UserTokenConsumeRace|UserSessionLookup|UserSessionEnd|UserEndOldestAppSessions|UserPendingEmail|UserActivateAndPeekToken|UserLatestToken|UserDeleteStaleUnverified|UserDeleteCascade|UserList|UserDeleteExpiredAuth|UserTextClipped|UserAtlas|UserAtlasConcurrentWriters|TelemetryRequests|TelemetryRequestsLimitRace|TelemetryRequestPollerState|RequestedTargetsEndToEnd|RequestedLocalTargetKeepsBeingLocal|RequestObserversApproved|RequestedAdminStateAndOffline|PollingOwnerRowsRequested|RequestedReportsFromAnUnassignedObserverAreIgnored|RequestedPasswordOnlyGoesToAnObserverApprovedNow|UserLoginSerialisedWithReset|UserAppExchangeSerialisedWithReset|UserAppSessionCapSerialised|UserResetTokenBoundToItsAddress|UserResendRecoversAnExpiredLink|UserPendingSignupKeptForSevenDays|UserAppExchangeAfterAResetBetweenSpendAndIssue|UserChangePasswordAfterAReset|UserChangePasswordRefusesAnEndedSession|UserChangeEmailAfterAReset|UserDeleteAccountAfterAReset|UserDeleteAccountKeepsRequestsWhenAResetLandsInTheGap|NodeReadingsKeepTheMethod|PortalUsers|PortalUsersConcurrentFirstSignIn|PortalStateIsConsumedOnce|PortalUserAppCodeAndDelete|AlertRules|AlertRulesRaceWithAtlasWrite|UserDevices|DeviceTokenMovesAcrossUsers|AlertEvaluationPass|AlertEvaluationGuard|AlertApplySkipsEditedRules|AlertEmailDelivery|AlertPushDelivery|AlertOutboxRetriesThenDrops|AlertSendGuard|AlertBackOnlineNeedsEnabledGoneQuiet|UserResetAfterAPasswordChange|UserTwoResetLinks|DeviceTokenSimultaneousRegistrations|UserAtlasReadIsOneSnapshot|UserAtlasLegacyPin|RequestedSeatsGoToOlderRequestsInOrder|RequestedSeatsTwoTargetRace|RequestedAdminStopIsTiedToThePasswordServed|RequestedOfflineSweepRechecksUnderTheLock|AlertEmailStaysPendingUntilSent|AlertPushPerDevice|AlertChannels|AlertChannelsRetryOnlyWhatFailed|AlertChannelsOffFinishTheRow|AlertEmailGroupsAreNotSplit|AlertObserverThatIsAlsoANode|AlertClockNeedsConsecutiveAdverts|AlertPolledNeedsACurrentSource|AlertEvaluationCursor|AlertPushFailureNeverDropsUnsentMail|AlertPushQuotaHoldNeverHoldsMail|AlertPushSlowRelayDeliversEverything|AlertValuelessNoticesSendNull|AlertPushRateLimitHoldsWithoutAttempts|AlertOutboxChannelMigration|OperatorDeleteNewRequest|ResetAfterDisable|SupersededEmailVerification|EmailChangeAfterDisable|RequestedClaimArrivesMidElection|RequestedPreemptionPromotesAStandby|RequestedPreemptionAndCleanupDoNotDeadlock|RequestedCleanupKeepsANewAssignment|RequestedOwnersOnAReadOnlyStoreFails|AlertRebootBeyondTwelveReadings|AlertClockBreachBetweenPasses|AlertTelemetryStopsWhenPollingIsOff|AlertMailWaitsForTheFinishedPass|DeleteUserNewTargetNoDeadlock|AdminStopReportRacesElection|AdminStopReportSurvivesTransientFailure|LocalAssignmentDoesNotPreemptRequest|CleanupKeepsDenseRanksAndStatus|OwnersApprovalReadErrorFailsAnswer|PreemptionOffersReplacementAtZeroFreeSlots|OfflineKeepsCredentialStops|DeletingRequestHasIndexedReverseReference|OwnersOfferSkipsWithdrawnTargets|RequestedInterleavingsKeepInvariants|OwnersPasswordFromOneSnapshot|StaleLoginFailedAfterWorkingPoll|OwnersLatestReadingBounded|StaleLoginFailedSurvivesReadingCleanup|AssigneeTrustedReadingBounded|WithdrawnTargetFreesItsSeat|ClockDriftKeepsSixteen|EmptyRegionListFilters|ObservationSignalNullAndZero|NodeActivityMatchesRaw|TraceWirePathBytes)Postgres$' -count=1 -v + run: go test ./db -timeout 25m -run '^Test(Signal|Paths|PacketSummaries|PacketEndpointsResolveLive|ObserverMetrics|ObserverDirectoryLiveCountsMatchRaw|ObserverActivityLiveCountsMatchRaw|RouteEvidence|RouteEvidenceIndex|AnalyticsRetention|AnalyticsRetentionConcurrent|DeleteOldPacketsBatches|MeshMapperCatalogue|ChannelMessageScopes|NodeLocationReset|RunMigrations[A-Za-z]*|KnownRoutesIndexSet|PacketsDomainChecks|Reconfirm[A-Za-z]*|BigintCursors|RouteSearchHopOrder|StatsNodeTypesSplit|ListKnownRoutes|ListKnownRoutesMatchesLegacy|KnownRoutesCursorTies|KnownRoutesUnanalyzedRegion|KnownRoutesHopStatementsStayCustom|GlobalHopBranchesMatchToday|KnownRoutePaginationTies|KnownRoutesByIATAsMatchMerge|KnownRoutesByIATAsBounded|RouteRetentionCutoffsExact|DeleteExpiredRoutes|DeleteGraceRoutesSlice|GraceWatermarkHeldByLockedRow|OpenPoolsSettings|PlanRouterClassCUnnamed|PlanRouterParallelWorkers|APIStoreHopStatementsUnnamed|PgStatStatementsMigrationGuarded|DBStatements|DBStatementsNoExtension|PgStatStatementsMigrationNoCreatableSchema|IndexHealthBaselineOnReindex|UnusedIndexes|PgActivity|RollHourSetsWorkMem|RollupWritesKeyOrder|SmallTableIndexSet|NodeReadersAfterIndexDrops|ClockDriftWideValues|ObserverChannelReadersAfterIndexDrops|UpsertChannelWriteThrough|UpsertChannelHashOnlyWriteThrough|ChannelHashOnlyRehear|ReadOnlyPoolsRejectWrites|ListPacketsGlobalMatchesLegacy|PacketsGlobalCursorTies|ListPacketsWindowInvertedRows|PacketsLatestObserverTie|NodesLegacyCursorMatchesToday|NodesPageCursorTies|ListNodesSorted|ObserversLegacyCursorMatchesToday|ObserversNextCursorFromLastSeen|ObserverAdvertsPartialIndex|ObserverComparisonMatchesToday|AdvertsWaitForPayloadTypeBackfill|StatsProbeMatchesToday|TraceTagsKeysetMatchesToday|TelemetrySinceMatchesCatchAll|TraceTagPagination|TraceTagPaginationTies|TraceSummarySurvivesMissedHearing|CmiMigrationsIndexSet|InsertChannelMessageSeed[A-Za-z]*|AddChannelMessageIATA|CmiSeedAndAddRace|CmiInitAndBackfill|CmiMessageRangeReconcile|CmiObservationRangeReconcile|CmiBackfillRetries23503|WaitForPreBootWriters|ChannelMessagesByIATAsMatchesLegacy|ChannelMessagesZeroHitRegion|CmiTrustLifecycle|CmiFirstVerification|PacketSitesMigrationsIndexSet|InsertObservationMaintainsPacketSites|InsertObservationResendWritesNothing|PacketSitesRaceMaxMerge|InsertObservationSiteFallback|PacketSitesInitAndBackfill|FillPacketSitesSliceIdempotent|FillPacketSitesSliceRetries23503|PacketSitesReconcile|PacketSitesAudit|PacketSitesAuditTakesNewestHearing|PacketsBySitesMatchesTruth|PacketsBySitesCursorTies|PacketsBySitesManyBogusSites|PacketsBySitesSaturatedPagesFull|PacketsBySitesMatchesLegacy|PacketSitesTrustLifecycle|PacketsBySitesBounded|PacketsBySitesFallbackKeepsPageCursor|PacketsBySitesFarWindow|SweepPacketSitesFrontsPlan|IndexHealthPacketSitesFreshBaseline|PacketSitesFirstVerification|PacketSitesBackfillSlicesSparseIDs|PacketSitesBackfillResumesAcrossGaps|PacketSitesProgressCountsRows|PacketSitesAuditSamplesRows|PacketSitesVerifySamplesRows|PacedBackfillSlices|FillSessionsPlanCustom|FillAnalyzeFailureIsIgnored|FillAnalyzeOnlyNeverAnalyzed|HygieneIndexSet|HygieneReadersAfterIndexDrops|KnownRoutesColumns|SequenceUse|SequenceUseMixedCaseSchema|ObservationsIndexSet|ReadersAfterIndexDrops|PollingClaimReplaceIsSnapshot|PollingClaimOlderIsIgnored|PollingClaimLimits|PollingForeignClaims|PollingForeignClaimTwoRoutes|PollingForeignRequestNeedsAcknowledgement|NodePollerForeign|NodePollerLocal|PollingForeignClaimedIsPerTarget|PollingForeignReadingNeedsApproval|PollingForeignRequestedAssignment|PollingForeignReadingNeverLatest|PollingDropUnplacedClaims|PacketBrokers|ObserverBrokersLastThirtyDays|PollingClaimTruncatesText|RepeaterReadingDedup|RepeaterReadingWithoutTagUsesSampledAt|PollingCandidatesEvidence|PollingAssignmentsOnePoller|PollingOwnerRowsLatestTs|CorroborateReadings|PollingLivenessUsesReceiveTime|PollingDeleteExpiredAndFlags|CorroborateReadingsUncountedFirst|CorroborateReadingsReachesEveryReading|ListPollingObservers|RepeaterReadingOutlivesObserver|RepeaterReadingTrustedAtInsert|RepeaterReadingTrustMigrationBackfill|PollingObserverIndexes|PollingElectionConcurrent|PollingOwnerRowsTrustedLatest|RepeaterReadingRateLimit|PollingClaimReceivedAt|PollingTargetsAdmin|PollingCandidatesEvidenceSince|PollingElectionLock|PollingEvidenceOutranksHealthyStranger|PollingApprovedAuthority|PollingClaimInterval|PollingClaimIntervalConcurrent|RepeaterReadingRateLimitConcurrent|RepeaterReadingObserverBudget|RepeaterReadingConstraints|RepeaterReadingWaitsForOpenInsert|PollingOrphanCleanupWaitsForElection|PollingLockKeys|NodeReadings|NodePolling|NodePoller|NodePollerReadIsOneSnapshot|ListLatestNodeReadings|UserCreateAndLookup|UserDuplicates|UserTokenConsume|UserTokenConsumeRace|UserSessionLookup|UserSessionEnd|UserEndOldestAppSessions|UserPendingEmail|UserActivateAndPeekToken|UserLatestToken|UserDeleteStaleUnverified|UserDeleteCascade|UserList|UserDeleteExpiredAuth|UserTextClipped|UserAtlas|UserAtlasConcurrentWriters|TelemetryRequests|TelemetryRequestsLimitRace|TelemetryRequestPollerState|RequestedTargetsEndToEnd|RequestedLocalTargetKeepsBeingLocal|RequestObserversApproved|RequestedAdminStateAndOffline|PollingOwnerRowsRequested|RequestedReportsFromAnUnassignedObserverAreIgnored|RequestedPasswordOnlyGoesToAnObserverApprovedNow|UserLoginSerialisedWithReset|UserAppExchangeSerialisedWithReset|UserAppSessionCapSerialised|UserResetTokenBoundToItsAddress|UserResendRecoversAnExpiredLink|UserPendingSignupKeptForSevenDays|UserAppExchangeAfterAResetBetweenSpendAndIssue|UserChangePasswordAfterAReset|UserChangePasswordRefusesAnEndedSession|UserChangeEmailAfterAReset|UserDeleteAccountAfterAReset|UserDeleteAccountKeepsRequestsWhenAResetLandsInTheGap|NodeReadingsKeepTheMethod|PortalUsers|PortalUsersConcurrentFirstSignIn|PortalStateIsConsumedOnce|PortalUserAppCodeAndDelete|AlertRules|AlertRulesRaceWithAtlasWrite|UserDevices|DeviceTokenMovesAcrossUsers|AlertEvaluationPass|AlertEvaluationGuard|AlertApplySkipsEditedRules|AlertEmailDelivery|AlertPushDelivery|AlertOutboxRetriesThenDrops|AlertSendGuard|AlertBackOnlineNeedsEnabledGoneQuiet|UserResetAfterAPasswordChange|UserTwoResetLinks|DeviceTokenSimultaneousRegistrations|UserAtlasReadIsOneSnapshot|UserAtlasLegacyPin|RequestedSeatsGoToOlderRequestsInOrder|RequestedSeatsTwoTargetRace|RequestedAdminStopIsTiedToThePasswordServed|RequestedOfflineSweepRechecksUnderTheLock|AlertEmailStaysPendingUntilSent|AlertPushPerDevice|AlertChannels|AlertChannelsRetryOnlyWhatFailed|AlertChannelsOffFinishTheRow|AlertEmailGroupsAreNotSplit|AlertObserverThatIsAlsoANode|AlertClockNeedsConsecutiveAdverts|AlertPolledNeedsACurrentSource|AlertEvaluationCursor|AlertPushFailureNeverDropsUnsentMail|AlertPushQuotaHoldNeverHoldsMail|AlertPushSlowRelayDeliversEverything|AlertValuelessNoticesSendNull|AlertPushRateLimitHoldsWithoutAttempts|AlertOutboxChannelMigration|OperatorDeleteNewRequest|ResetAfterDisable|SupersededEmailVerification|EmailChangeAfterDisable|RequestedClaimArrivesMidElection|RequestedPreemptionPromotesAStandby|RequestedPreemptionAndCleanupDoNotDeadlock|RequestedCleanupKeepsANewAssignment|RequestedOwnersOnAReadOnlyStoreFails|AlertRebootBeyondTwelveReadings|AlertClockBreachBetweenPasses|AlertTelemetryStopsWhenPollingIsOff|AlertMailWaitsForTheFinishedPass|DeleteUserNewTargetNoDeadlock|AdminStopReportRacesElection|AdminStopReportSurvivesTransientFailure|LocalAssignmentDoesNotPreemptRequest|CleanupKeepsDenseRanksAndStatus|OwnersApprovalReadErrorFailsAnswer|PreemptionOffersReplacementAtZeroFreeSlots|OfflineKeepsCredentialStops|DeletingRequestHasIndexedReverseReference|OwnersOfferSkipsWithdrawnTargets|RequestedInterleavingsKeepInvariants|OwnersPasswordFromOneSnapshot|StaleLoginFailedAfterWorkingPoll|OwnersLatestReadingBounded|StaleLoginFailedSurvivesReadingCleanup|AssigneeTrustedReadingBounded|WithdrawnTargetFreesItsSeat|ClockDriftKeepsSixteen|EmptyRegionListFilters|ObservationSignalNullAndZero|NodeActivityMatchesRaw|TraceWirePathBytes)Postgres$' -count=1 -v - name: Verify the channel message site rule against PostgreSQL 16 env: diff --git a/cmd/beacon/main.go b/cmd/beacon/main.go index bc758b37..8e088d46 100644 --- a/cmd/beacon/main.go +++ b/cmd/beacon/main.go @@ -56,7 +56,7 @@ import ( var version = "dev" // @title MeshCore Beacon API -// @version 2.3.2 +// @version 2.3.3 // @description MeshCore network observation backend. Ingests LoRa packets from MQTT brokers, stores in PostgreSQL, and streams live events via WebSocket. // @description REST requests share a configurable per-client rate limit (default 600/minute and a 600-request one-second burst cap). Exceeded limits return HTTP 429 with error.code=rate_limited and a Retry-After header in seconds. CORS preflights and WebSocket upgrades do not consume this API budget. // @description WebSocket upgrade attempts at /ws have a configurable per-client limit (default 10/minute, including failed handshakes). Rate exhaustion returns HTTP 429 with Retry-After before upgrade. An accepted socket exceeding the concurrent cap closes with code 1013 before hello; established connections remain open. diff --git a/db/migrations/095_repeater_readings_foreign_observer_index.sql b/db/migrations/095_repeater_readings_foreign_observer_index.sql new file mode 100644 index 00000000..634aaad5 --- /dev/null +++ b/db/migrations/095_repeater_readings_foreign_observer_index.sql @@ -0,0 +1,7 @@ +-- Copyright 2026 Beacon Contributors +-- SPDX-License-Identifier: AGPL-3.0-or-later + +-- Finds the foreign readings of one observer by receive time, for the local poller flag on nodes and its poller +-- view. Partial, so it stays empty on a server that stores none. +-- Its own file so CONCURRENTLY runs outside a transaction. The runner rebuilds it if a build was cut short. +CREATE INDEX CONCURRENTLY idx_repeater_readings_foreign_observer ON repeater_readings USING btree (observer_public_key, received_at DESC) WHERE foreign_source; diff --git a/db/nodes.go b/db/nodes.go index a59d6a5e..dc3a9186 100644 --- a/db/nodes.go +++ b/db/nodes.go @@ -198,7 +198,7 @@ func (s *Store) ListNodesSorted(ctx context.Context, nodeType int16, iatas []str items = append(items, s.nodeSummary(sqlc.ListNodesRow{ ID: v.ID, PublicKey: v.PublicKey, NodeType: v.NodeType, Name: v.Name, Latitude: v.Latitude, Longitude: v.Longitude, LastSeen: v.LastSeen, RadioFreqMhz: v.RadioFreqMhz, RadioSf: v.RadioSf, - RadioBwKhz: v.RadioBwKhz, DefaultScopeName: v.DefaultScopeName, Iatas: v.Iatas, IsObserver: v.IsObserver, IsPoller: v.IsPoller, IsForeignPoller: v.IsForeignPoller, + RadioBwKhz: v.RadioBwKhz, DefaultScopeName: v.DefaultScopeName, Iatas: v.Iatas, IsObserver: v.IsObserver, IsPoller: v.IsPoller, IsForeignPoller: v.IsForeignPoller, IsLocalPoller: v.IsLocalPoller, ObserverID: v.ObserverID, KnownNeighborCount: v.KnownNeighborCount, NeighborIds: v.NeighborIds, })) } @@ -224,6 +224,7 @@ func (s *Store) nodeSummary(v sqlc.ListNodesRow) api.NodeSummary { IsObserver: v.IsObserver, IsPoller: v.IsPoller, IsForeignPoller: v.IsForeignPoller, + IsLocalPoller: v.IsLocalPoller, ObserverID: nullableUUID(v.ObserverID), DefaultScope: v.DefaultScopeName, KnownNeighborCount: v.KnownNeighborCount, @@ -261,6 +262,7 @@ func (s *Store) GetNode(ctx context.Context, nodeID uuid.UUID) (*api.Node, error IsObserver: row.IsObserver, IsPoller: row.IsPoller, IsForeignPoller: row.IsForeignPoller, + IsLocalPoller: row.IsLocalPoller, ObserverID: nullableUUID(row.ObserverID), DefaultScope: row.DefaultScopeName, KnownNeighborCount: row.KnownNeighborCount, diff --git a/db/packets_legacy_test.go b/db/packets_legacy_test.go index 3e7c0c71..70914c22 100644 --- a/db/packets_legacy_test.go +++ b/db/packets_legacy_test.go @@ -116,6 +116,7 @@ SELECT n.id, n.public_key, n.node_type, n.name, n.latitude, n.longitude, n.last_ EXISTS (SELECT 1 FROM observers o WHERE o.public_key = n.public_key) AS is_observer, false AS is_poller, -- no claims in this fixture false AS is_foreign_poller, + false AS is_local_poller, (SELECT o.id FROM observers o WHERE o.public_key = n.public_key LIMIT 1) AS observer_id, (SELECT COUNT(DISTINCT nn.neighbor_id) FROM node_neighbors nn WHERE nn.node_id = n.id)::bigint AS known_neighbor_count, (CASE WHEN $10::bool THEN diff --git a/db/planguard/baseline/fixture/sm.node.top_sea.auto.json b/db/planguard/baseline/fixture/sm.node.top_sea.auto.json index a0241353..d70bcb61 100644 --- a/db/planguard/baseline/fixture/sm.node.top_sea.auto.json +++ b/db/planguard/baseline/fixture/sm.node.top_sea.auto.json @@ -5,7 +5,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Index Only Scan on polling_claims c using polling_claims_pkey scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Index Only Scan on polling_claims c_1 using polling_claims_pkey scan=Forward [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.node.top_sea.custom.json b/db/planguard/baseline/fixture/sm.node.top_sea.custom.json index a0241353..d70bcb61 100644 --- a/db/planguard/baseline/fixture/sm.node.top_sea.custom.json +++ b/db/planguard/baseline/fixture/sm.node.top_sea.custom.json @@ -5,7 +5,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Index Only Scan on polling_claims c using polling_claims_pkey scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Index Only Scan on polling_claims c_1 using polling_claims_pkey scan=Forward [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.node.top_sea.generic.json b/db/planguard/baseline/fixture/sm.node.top_sea.generic.json index a0241353..d70bcb61 100644 --- a/db/planguard/baseline/fixture/sm.node.top_sea.generic.json +++ b/db/planguard/baseline/fixture/sm.node.top_sea.generic.json @@ -5,7 +5,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Index Only Scan on polling_claims c using polling_claims_pkey scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Index Only Scan on polling_claims c_1 using polling_claims_pkey scan=Forward [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.node.unknown.auto.json b/db/planguard/baseline/fixture/sm.node.unknown.auto.json index a0241353..d70bcb61 100644 --- a/db/planguard/baseline/fixture/sm.node.unknown.auto.json +++ b/db/planguard/baseline/fixture/sm.node.unknown.auto.json @@ -5,7 +5,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Index Only Scan on polling_claims c using polling_claims_pkey scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Index Only Scan on polling_claims c_1 using polling_claims_pkey scan=Forward [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.node.unknown.custom.json b/db/planguard/baseline/fixture/sm.node.unknown.custom.json index a0241353..d70bcb61 100644 --- a/db/planguard/baseline/fixture/sm.node.unknown.custom.json +++ b/db/planguard/baseline/fixture/sm.node.unknown.custom.json @@ -5,7 +5,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Index Only Scan on polling_claims c using polling_claims_pkey scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Index Only Scan on polling_claims c_1 using polling_claims_pkey scan=Forward [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.node.unknown.generic.json b/db/planguard/baseline/fixture/sm.node.unknown.generic.json index a0241353..d70bcb61 100644 --- a/db/planguard/baseline/fixture/sm.node.unknown.generic.json +++ b/db/planguard/baseline/fixture/sm.node.unknown.generic.json @@ -5,7 +5,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Index Only Scan on polling_claims c using polling_claims_pkey scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Index Only Scan on polling_claims c_1 using polling_claims_pkey scan=Forward [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.node_local_poller.absent.custom.json b/db/planguard/baseline/fixture/sm.node_local_poller.absent.custom.json new file mode 100644 index 00000000..dffa4e05 --- /dev/null +++ b/db/planguard/baseline/fixture/sm.node_local_poller.absent.custom.json @@ -0,0 +1,11 @@ +[ + "Limit", + " Sort", + " Nested Loop (Left)", + " Nested Loop (Left)", + " Unique", + " Index Only Scan on repeater_readings r using idx_repeater_readings_foreign_target scan=Forward", + " Index Scan on nodes n using nodes_public_key_key scan=Forward", + " Limit", + " Index Scan on repeater_readings r_1 using idx_repeater_readings_target_observer scan=Forward" +] diff --git a/db/planguard/baseline/fixture/sm.node_local_poller.busy.custom.json b/db/planguard/baseline/fixture/sm.node_local_poller.busy.custom.json new file mode 100644 index 00000000..dffa4e05 --- /dev/null +++ b/db/planguard/baseline/fixture/sm.node_local_poller.busy.custom.json @@ -0,0 +1,11 @@ +[ + "Limit", + " Sort", + " Nested Loop (Left)", + " Nested Loop (Left)", + " Unique", + " Index Only Scan on repeater_readings r using idx_repeater_readings_foreign_target scan=Forward", + " Index Scan on nodes n using nodes_public_key_key scan=Forward", + " Limit", + " Index Scan on repeater_readings r_1 using idx_repeater_readings_target_observer scan=Forward" +] diff --git a/db/planguard/baseline/fixture/sm.nodes.SEA.custom.json b/db/planguard/baseline/fixture/sm.nodes.SEA.custom.json index b60a57eb..803552b3 100644 --- a/db/planguard/baseline/fixture/sm.nodes.SEA.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.SEA.custom.json @@ -14,7 +14,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.SEA_type2.custom.json b/db/planguard/baseline/fixture/sm.nodes.SEA_type2.custom.json index b60a57eb..803552b3 100644 --- a/db/planguard/baseline/fixture/sm.nodes.SEA_type2.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.SEA_type2.custom.json @@ -14,7 +14,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.bogus5000.custom.json b/db/planguard/baseline/fixture/sm.nodes.bogus5000.custom.json index 3d44b674..6d3fd400 100644 --- a/db/planguard/baseline/fixture/sm.nodes.bogus5000.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.bogus5000.custom.json @@ -13,7 +13,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.first_l201_neighbors_SEA.custom.json b/db/planguard/baseline/fixture/sm.nodes.first_l201_neighbors_SEA.custom.json index b60a57eb..803552b3 100644 --- a/db/planguard/baseline/fixture/sm.nodes.first_l201_neighbors_SEA.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.first_l201_neighbors_SEA.custom.json @@ -14,7 +14,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.first_l501.custom.json b/db/planguard/baseline/fixture/sm.nodes.first_l501.custom.json index e9f6569e..941a04e9 100644 --- a/db/planguard/baseline/fixture/sm.nodes.first_l501.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.first_l501.custom.json @@ -12,7 +12,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.global.custom.json b/db/planguard/baseline/fixture/sm.nodes.global.custom.json index e9f6569e..941a04e9 100644 --- a/db/planguard/baseline/fixture/sm.nodes.global.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.global.custom.json @@ -12,7 +12,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.global_deep_cursor200.custom.json b/db/planguard/baseline/fixture/sm.nodes.global_deep_cursor200.custom.json index e9f6569e..941a04e9 100644 --- a/db/planguard/baseline/fixture/sm.nodes.global_deep_cursor200.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.global_deep_cursor200.custom.json @@ -12,7 +12,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.legacy_cursor_l501.custom.json b/db/planguard/baseline/fixture/sm.nodes.legacy_cursor_l501.custom.json index e9f6569e..941a04e9 100644 --- a/db/planguard/baseline/fixture/sm.nodes.legacy_cursor_l501.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.legacy_cursor_l501.custom.json @@ -12,7 +12,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.multibyte_true.custom.json b/db/planguard/baseline/fixture/sm.nodes.multibyte_true.custom.json index 878680f2..c16c2e03 100644 --- a/db/planguard/baseline/fixture/sm.nodes.multibyte_true.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.multibyte_true.custom.json @@ -11,7 +11,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Index Only Scan on polling_claims c using polling_claims_pkey scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Index Only Scan on polling_claims c_1 using polling_claims_pkey scan=Forward [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.name_a.custom.json b/db/planguard/baseline/fixture/sm.nodes.name_a.custom.json index 878680f2..c16c2e03 100644 --- a/db/planguard/baseline/fixture/sm.nodes.name_a.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.name_a.custom.json @@ -11,7 +11,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Index Only Scan on polling_claims c using polling_claims_pkey scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Index Only Scan on polling_claims c_1 using polling_claims_pkey scan=Forward [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.pagecursor_l501.custom.json b/db/planguard/baseline/fixture/sm.nodes.pagecursor_l501.custom.json index e9f6569e..941a04e9 100644 --- a/db/planguard/baseline/fixture/sm.nodes.pagecursor_l501.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.pagecursor_l501.custom.json @@ -12,7 +12,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.poller_false.custom.json b/db/planguard/baseline/fixture/sm.nodes.poller_false.custom.json index f4e45374..f16f43fa 100644 --- a/db/planguard/baseline/fixture/sm.nodes.poller_false.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.poller_false.custom.json @@ -4,8 +4,9 @@ " Sort", " Hash Join (Left)", " Seq Scan on nodes n_1", - " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", - " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_3 [SubPlan]", + " Index Only Scan on repeater_readings lr_2 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", " Hash", " Seq Scan on transport_scopes ts", " Aggregate partial=Simple [SubPlan]", @@ -14,7 +15,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.poller_true.custom.json b/db/planguard/baseline/fixture/sm.nodes.poller_true.custom.json index eef93b96..f7fb2913 100644 --- a/db/planguard/baseline/fixture/sm.nodes.poller_true.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.poller_true.custom.json @@ -4,8 +4,9 @@ " Sort", " Hash Join (Left)", " Seq Scan on nodes n_1", - " Seq Scan on polling_claims c_1 [SubPlan]", - " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_3 [SubPlan]", + " Index Only Scan on repeater_readings lr_2 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Hash", " Seq Scan on transport_scopes ts", " Aggregate partial=Simple [SubPlan]", @@ -14,7 +15,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.poller_true_type2.custom.json b/db/planguard/baseline/fixture/sm.nodes.poller_true_type2.custom.json index eef93b96..f7fb2913 100644 --- a/db/planguard/baseline/fixture/sm.nodes.poller_true_type2.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.poller_true_type2.custom.json @@ -4,8 +4,9 @@ " Sort", " Hash Join (Left)", " Seq Scan on nodes n_1", - " Seq Scan on polling_claims c_1 [SubPlan]", - " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_3 [SubPlan]", + " Index Only Scan on repeater_readings lr_2 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Hash", " Seq Scan on transport_scopes ts", " Aggregate partial=Simple [SubPlan]", @@ -14,7 +15,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.pubkey_prefix.custom.json b/db/planguard/baseline/fixture/sm.nodes.pubkey_prefix.custom.json index 0df14ae9..279026b7 100644 --- a/db/planguard/baseline/fixture/sm.nodes.pubkey_prefix.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.pubkey_prefix.custom.json @@ -11,7 +11,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.traces_true.custom.json b/db/planguard/baseline/fixture/sm.nodes.traces_true.custom.json index 878680f2..c16c2e03 100644 --- a/db/planguard/baseline/fixture/sm.nodes.traces_true.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.traces_true.custom.json @@ -11,7 +11,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Index Only Scan on polling_claims c using polling_claims_pkey scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Index Only Scan on polling_claims c_1 using polling_claims_pkey scan=Forward [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.type1.custom.json b/db/planguard/baseline/fixture/sm.nodes.type1.custom.json index e9f6569e..941a04e9 100644 --- a/db/planguard/baseline/fixture/sm.nodes.type1.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.type1.custom.json @@ -12,7 +12,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.type2.custom.json b/db/planguard/baseline/fixture/sm.nodes.type2.custom.json index e9f6569e..941a04e9 100644 --- a/db/planguard/baseline/fixture/sm.nodes.type2.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.type2.custom.json @@ -12,7 +12,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.type2_deep_cursor.custom.json b/db/planguard/baseline/fixture/sm.nodes.type2_deep_cursor.custom.json index e9f6569e..941a04e9 100644 --- a/db/planguard/baseline/fixture/sm.nodes.type2_deep_cursor.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.type2_deep_cursor.custom.json @@ -12,7 +12,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.type3.custom.json b/db/planguard/baseline/fixture/sm.nodes.type3.custom.json index e9f6569e..941a04e9 100644 --- a/db/planguard/baseline/fixture/sm.nodes.type3.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.type3.custom.json @@ -12,7 +12,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_1 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes.type9_empty.custom.json b/db/planguard/baseline/fixture/sm.nodes.type9_empty.custom.json index 878680f2..c16c2e03 100644 --- a/db/planguard/baseline/fixture/sm.nodes.type9_empty.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes.type9_empty.custom.json @@ -11,7 +11,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Index Only Scan on polling_claims c using polling_claims_pkey scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Index Only Scan on polling_claims c_1 using polling_claims_pkey scan=Forward [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes_sorted.last_seen.custom.json b/db/planguard/baseline/fixture/sm.nodes_sorted.last_seen.custom.json index 2d34cbd1..4234058c 100644 --- a/db/planguard/baseline/fixture/sm.nodes_sorted.last_seen.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes_sorted.last_seen.custom.json @@ -19,7 +19,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c_1 [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes_sorted.last_seen_cursor.custom.json b/db/planguard/baseline/fixture/sm.nodes_sorted.last_seen_cursor.custom.json index 2d34cbd1..4234058c 100644 --- a/db/planguard/baseline/fixture/sm.nodes_sorted.last_seen_cursor.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes_sorted.last_seen_cursor.custom.json @@ -19,7 +19,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c_1 [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes_sorted.name.custom.json b/db/planguard/baseline/fixture/sm.nodes_sorted.name.custom.json index 48dece44..5da3f68f 100644 --- a/db/planguard/baseline/fixture/sm.nodes_sorted.name.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes_sorted.name.custom.json @@ -19,7 +19,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c_1 [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes_sorted.name_desc_cursor.custom.json b/db/planguard/baseline/fixture/sm.nodes_sorted.name_desc_cursor.custom.json index 48dece44..5da3f68f 100644 --- a/db/planguard/baseline/fixture/sm.nodes_sorted.name_desc_cursor.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes_sorted.name_desc_cursor.custom.json @@ -19,7 +19,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c_1 [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes_sorted.neighbors_desc.custom.json b/db/planguard/baseline/fixture/sm.nodes_sorted.neighbors_desc.custom.json index cbb34a84..dededef3 100644 --- a/db/planguard/baseline/fixture/sm.nodes_sorted.neighbors_desc.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes_sorted.neighbors_desc.custom.json @@ -19,7 +19,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c_1 [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes_sorted.poller_false.custom.json b/db/planguard/baseline/fixture/sm.nodes_sorted.poller_false.custom.json index 54a30ecf..909d0ce1 100644 --- a/db/planguard/baseline/fixture/sm.nodes_sorted.poller_false.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes_sorted.poller_false.custom.json @@ -9,8 +9,9 @@ " Nested Loop (Left)", " Hash Join (Left)", " Seq Scan on nodes n_1", - " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", - " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_3 [SubPlan]", + " Index Only Scan on repeater_readings lr_2 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", + " Seq Scan on polling_claims c_3 [SubPlan]", " Hash", " Seq Scan on transport_scopes ts", " CTE Scan", @@ -20,7 +21,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c_1 [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes_sorted.poller_true.custom.json b/db/planguard/baseline/fixture/sm.nodes_sorted.poller_true.custom.json index a0df5c9c..f2608a6c 100644 --- a/db/planguard/baseline/fixture/sm.nodes_sorted.poller_true.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes_sorted.poller_true.custom.json @@ -6,22 +6,26 @@ " Subquery Scan", " Limit [Subquery]", " Sort", - " Hash Join (Left)", + " Nested Loop (Left)", " Hash Join (Left)", " Seq Scan on nodes n_1", - " Seq Scan on polling_claims c_2 [SubPlan]", - " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Seq Scan on polling_claims c_3 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_3 [SubPlan]", + " Index Only Scan on repeater_readings lr_2 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Hash", " Seq Scan on transport_scopes ts", - " Hash", - " CTE Scan", + " CTE Scan", " Aggregate partial=Simple [SubPlan]", " Sort", " Index Scan on node_iatas ni using node_iatas_pkey scan=Forward", " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c_1 [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes_sorted.poller_true_type2.custom.json b/db/planguard/baseline/fixture/sm.nodes_sorted.poller_true_type2.custom.json index b3ca76fa..f2608a6c 100644 --- a/db/planguard/baseline/fixture/sm.nodes_sorted.poller_true_type2.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes_sorted.poller_true_type2.custom.json @@ -9,8 +9,9 @@ " Nested Loop (Left)", " Hash Join (Left)", " Seq Scan on nodes n_1", - " Seq Scan on polling_claims c_2 [SubPlan]", - " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Seq Scan on polling_claims c_3 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_3 [SubPlan]", + " Index Only Scan on repeater_readings lr_2 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Hash", " Seq Scan on transport_scopes ts", " CTE Scan", @@ -20,7 +21,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c_1 [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/baseline/fixture/sm.nodes_sorted.type_SEA.custom.json b/db/planguard/baseline/fixture/sm.nodes_sorted.type_SEA.custom.json index 5c626520..be6d25e1 100644 --- a/db/planguard/baseline/fixture/sm.nodes_sorted.type_SEA.custom.json +++ b/db/planguard/baseline/fixture/sm.nodes_sorted.type_SEA.custom.json @@ -21,7 +21,11 @@ " Index Only Scan on observers o using observers_public_key_key scan=Forward [SubPlan]", " Seq Scan on polling_claims c_1 [SubPlan]", " Seq Scan on polling_foreign_claims fc [SubPlan]", + " Index Only Scan on repeater_readings lr using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Seq Scan on polling_foreign_claims fc_1 [SubPlan]", + " Seq Scan on polling_claims c_2 [SubPlan]", + " Seq Scan on polling_foreign_claims fc_2 [SubPlan]", + " Index Only Scan on repeater_readings lr_1 using idx_repeater_readings_foreign_observer scan=Forward [SubPlan]", " Limit [SubPlan]", " Index Scan on observers o_1 using observers_public_key_key scan=Forward", " Aggregate partial=Simple [SubPlan]", diff --git a/db/planguard/corpus.yaml b/db/planguard/corpus.yaml index d2af3626..280e90fe 100644 --- a/db/planguard/corpus.yaml +++ b/db/planguard/corpus.yaml @@ -117,6 +117,8 @@ statements: ListTraceTags: {sqlc: ListTraceTags, group: stats_adverts, plan: custom} # A node's own polling claim and the targets it names. NodePoller: {sqlc: NodePoller, plan: custom} + # The repeaters an observer with no claim sent readings for. + NodeLocalPollerTargets: {sqlc: NodeLocalPollerTargets, plan: custom} # One observer's adverts and telemetry pages. ListObserverAdverts: {sqlc: ListObserverAdverts, group: stats_adverts, plan: cached, admission: observer_page} GetObserverTelemetrySince: {sqlc: GetObserverTelemetrySince, group: stats_adverts, plan: cached, admission: observer_page} @@ -3222,6 +3224,22 @@ entries: expect: forbid: [{node: Seq Scan, relations: [repeater_readings], reason: "readings are counted and looked up through the observer and target indexes"}] note: "fixture and prod only, as sm.node_poller.busy" + - id: sm.node_local_poller.busy + stmt: NodeLocalPollerTargets + shape: "NodeLocalPollerTargets, an observer with readings" + params: [{r: poller_busy_key}, {r: poller_readings_after}, {raw: "32"}] + tiers: [fixture, prod] + expect: + forbid: [{node: Seq Scan, relations: [repeater_readings], reason: "foreign readings are found through the observer index and the newest through the target index"}] + note: "fixture and prod only, as sm.node_poller.busy" + - id: sm.node_local_poller.absent + stmt: NodeLocalPollerTargets + shape: "NodeLocalPollerTargets, a key with no readings" + params: [{raw: "'\\x0000000000000000000000000000000000000000000000000000000000000000'::bytea"}, {r: poller_readings_after}, {raw: "32"}] + tiers: [fixture, prod] + expect: + forbid: [{node: Seq Scan, relations: [repeater_readings], reason: "foreign readings are found through the observer index and the newest through the target index"}] + note: "fixture and prod only, as sm.node_poller.busy" - id: sm.nodes_sorted.name stmt: ListNodesSorted shape: "ListNodesSorted name" diff --git a/db/polling.go b/db/polling.go index bf8c84e9..684be4c5 100644 --- a/db/polling.go +++ b/db/polling.go @@ -42,7 +42,7 @@ func (s *Store) ObserverID(ctx context.Context, pubkey []byte) (uuid.UUID, error return id, err } -// IsPollerByPubkey reports whether the node has a polling claim; false on error. +// IsPollerByPubkey reports whether the node has a polling claim or sent claimless readings in the last day; false on error. func (s *Store) IsPollerByPubkey(ctx context.Context, pubkey []byte) bool { ok, err := s.q.IsPollerKey(ctx, pubkey) return err == nil && ok @@ -1042,6 +1042,9 @@ func (s *Store) GetNodePoller(ctx context.Context, nodeID uuid.UUID) (*api.NodeP return out, nil } +// localPollerTargetLimit caps the targets listed for an observer that sends no claim. +const localPollerTargetLimit = 32 + // foreignPoller fills the poller view of an observer with no claim of this server's own: its foreign claim and the // targets that names, when it has one, and the readings it delivered either way. func (s *Store) foreignPoller(ctx context.Context, key []byte, out *api.NodePoller, now time.Time) (*api.NodePoller, error) { @@ -1051,8 +1054,11 @@ func (s *Store) foreignPoller(ctx context.Context, key []byte, out *api.NodePoll } out.Readings24h, out.ForeignReadings24h = int(counts.Readings), int(counts.ForeignReadings) rows, err := s.q.NodeForeignPoller(ctx, key) - if err != nil || len(rows) == 0 { - return out, err + if err != nil { + return nil, err + } + if len(rows) == 0 { + return s.localPollerTargets(ctx, key, out, now) } cl := rows[0] slots := api.NodePollerSlots{Max: polling.MaxRequestSlots} @@ -1091,6 +1097,33 @@ func (s *Store) foreignPoller(ctx context.Context, key []byte, out *api.NodePoll return out, nil } +// localPollerTargets fills the targets of an observer that sends readings and no claim: the repeaters it sent foreign +// readings for in the last day. +func (s *Store) localPollerTargets(ctx context.Context, key []byte, out *api.NodePoller, now time.Time) (*api.NodePoller, error) { + if out.ForeignReadings24h == 0 { + return out, nil + } + rows, err := s.q.NodeLocalPollerTargets(ctx, sqlc.NodeLocalPollerTargetsParams{ + ObserverPublicKey: key, ReadingsAfter: ts(now.Add(-24 * time.Hour)), RowLimit: localPollerTargetLimit}) + if err != nil { + return nil, err + } + for _, r := range rows { + t := api.NodePollerTarget{PublicKey: hex.EncodeToString(r.TargetPublicKey), Role: "unassigned", LatestReadingAt: epochMs(r.LatestReadingAt), + LatestReadingRssi: ptrConv(r.LatestReadingRssi, func(v int16) int { return int(v) }), LatestReadingSigned: r.LatestReadingSigned} + if r.NodeID.Valid { + id := uuid.UUID(r.NodeID.Bytes) + t.NodeID = &id + } + if r.Name != "" { + name := r.Name + t.Name = &name + } + out.Targets = append(out.Targets, t) + } + return out, nil +} + // ListLatestNodeReadings returns each polled node's newest trusted battery and temperature since the given time. func (s *Store) ListLatestNodeReadings(ctx context.Context, iatas []string, since time.Time) ([]api.NodeLatestReading, error) { rows, err := s.q.LatestNodeReadings(ctx, sqlc.LatestNodeReadingsParams{Since: ts(since), Iatas: iatas}) diff --git a/db/polling_foreign_integration_test.go b/db/polling_foreign_integration_test.go index 2f75b1e3..1385af42 100644 --- a/db/polling_foreign_integration_test.go +++ b/db/polling_foreign_integration_test.go @@ -11,6 +11,7 @@ import ( "testing" "time" + "github.com/MeshCore-Beacon/beacon-server/internal/api" "github.com/MeshCore-Beacon/beacon-server/internal/config" "github.com/MeshCore-Beacon/beacon-server/internal/polling" "github.com/google/uuid" @@ -270,11 +271,11 @@ func TestNodePollerForeignPostgres(t *testing.T) { w.reading(local, tg, 2) foreignNode, localNode := nodeOf(foreign), nodeOf(local) - // The node flags: a foreign claim makes a poller, marked foreign; readings alone do not. - if n, err := s.GetNode(ctx, foreignNode); err != nil || !n.IsPoller || !n.IsForeignPoller { + // 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) } - if n, err := s.GetNode(ctx, localNode); err != nil || n.IsPoller || n.IsForeignPoller { + if n, err := s.GetNode(ctx, localNode); err != nil || !n.IsPoller || n.IsForeignPoller || !n.IsLocalPoller { t.Fatalf("readings-only node flags: %+v %v", n, err) } // A foreign observer with a claim: the claim is marked, its targets are all unassigned. @@ -287,13 +288,117 @@ func TestNodePollerForeignPostgres(t *testing.T) { !bytes.Equal(pollKey(tg), mustHex(t, tgt.PublicKey)) || tgt.LatestReadingAt == nil { t.Fatalf("target: %+v", p.Targets[0]) } - // One that only sends readings, as an observer in local mode does: no claim, but its readings are counted. + // One that only sends readings, as an observer in local mode does: no claim, its readings are counted and + // the repeater they were for is listed. p, err = s.GetNodePoller(ctx, localNode) - if err != nil || p.Claim != nil || p.Readings24h != 1 || p.ForeignReadings24h != 1 || len(p.Targets) != 0 { + if err != nil || p.Claim != nil || p.Readings24h != 1 || p.ForeignReadings24h != 1 || len(p.Targets) != 1 { t.Fatalf("reading-only: %+v %v", p, err) } } +func TestNodePollerLocalPostgres(t *testing.T) { + w := newForeignWorld(t) + ctx, s, pool := w.ctx, w.s, w.pool + local, stale, quiet := newReqDevice(2), newReqDevice(3), newReqDevice(4) + const tgA, tgB = byte(0xA1), byte(0xA2) + targetA := w.node(tgA) + nodeOf := func(d reqDevice, name string) uuid.UUID { + t.Helper() + pollObserver(t, ctx, s, d.pub) + var id uuid.UUID + if err := pool.QueryRow(ctx, `INSERT INTO nodes (public_key, node_type, name) VALUES ($1, 2, $2) RETURNING id`, d.pub, name).Scan(&id); err != nil { + t.Fatal(err) + } + return id + } + localNode, staleNode, quietNode := nodeOf(local, "Local"), nodeOf(stale, "Stale"), nodeOf(quiet, "Quiet") + // tgA is a known node read twice, tgB an unknown key read last, so it lists first. + w.reading(local, tgA, 1) + w.reading(stale, tgA, 2) + w.now = w.now.Add(10 * time.Minute) + w.reading(local, tgA, 3) + w.now = w.now.Add(10 * time.Minute) + w.reading(local, tgB, 4) + if _, err := pool.Exec(ctx, `UPDATE repeater_readings SET received_at = now() - interval '25 hours' WHERE observer_public_key = $1`, stale.pub); err != nil { + t.Fatal(err) + } + flags := func(id uuid.UUID) [3]bool { + t.Helper() + n, err := s.GetNode(ctx, id) + if err != nil { + t.Fatal(err) + } + return [3]bool{n.IsPoller, n.IsForeignPoller, n.IsLocalPoller} + } + // Foreign readings and no claim: a poller, local. A reading over a day old, or none, is neither. + if got := flags(localNode); got != [3]bool{true, false, true} { + t.Fatalf("local flags: %v", got) + } + if got := flags(staleNode); got != [3]bool{} { + t.Fatalf("stale flags: %v", got) + } + if got := flags(quietNode); got != [3]bool{} { + t.Fatalf("quiet flags: %v", got) + } + if !s.IsPollerByPubkey(ctx, local.pub) || s.IsPollerByPubkey(ctx, stale.pub) { + t.Fatal("IsPollerByPubkey: local must count, stale must not") + } + // Both lists carry the flag and the poller filter counts it. + yes, no := true, false + listed := func(sorted bool, poller *bool) map[string]api.NodeSummary { + t.Helper() + var page api.NodePage + var err error + if sorted { + page, err = s.ListNodesSorted(ctx, 0, nil, nil, nil, poller, nil, "", "", "", api.NodeSort{By: "name"}, nil, 50, false) + } else { + page, err = s.ListNodes(ctx, 0, nil, nil, nil, poller, nil, "", "", "", 0, nil, 50, false) + } + if err != nil { + t.Fatal(err) + } + out := map[string]api.NodeSummary{} + for _, it := range page.Items { + out[*it.Name] = it + } + return out + } + for _, sorted := range []bool{false, true} { + got := listed(sorted, &yes) + if n, ok := got["Local"]; len(got) != 1 || !ok || !n.IsPoller || !n.IsLocalPoller || n.IsForeignPoller { + t.Fatalf("sorted=%v poller=true: %+v", sorted, got) + } + got = listed(sorted, &no) + if _, ok := got["Local"]; ok || len(got) != 3 || got["Stale"].IsPoller || got["Stale"].IsLocalPoller { + t.Fatalf("sorted=%v poller=false: %+v", sorted, got) + } + } + // The poller view: no claim, one target per repeater read, newest reading first. + p, err := s.GetNodePoller(ctx, localNode) + if err != nil || p.Claim != nil || p.Readings24h != 3 || p.ForeignReadings24h != 3 || len(p.Targets) != 2 { + t.Fatalf("local poller: %+v %v", p, err) + } + if tgt := p.Targets[0]; !bytes.Equal(pollKey(tgB), mustHex(t, tgt.PublicKey)) || tgt.NodeID != nil || tgt.Name != nil || tgt.Role != "unassigned" { + t.Fatalf("first target: %+v", tgt) + } + if tgt := p.Targets[1]; !bytes.Equal(pollKey(tgA), mustHex(t, tgt.PublicKey)) || tgt.NodeID == nil || *tgt.NodeID != targetA || + tgt.Name == nil || *tgt.Name != "Hill" || tgt.Role != "unassigned" || tgt.Rank != nil || tgt.State != "" || + tgt.LatestReadingAt == nil || *tgt.LatestReadingAt != w.now.Add(-10*time.Minute).UnixMilli() || tgt.LatestReadingSigned { + t.Fatalf("second target: %+v", tgt) + } + if p, err = s.GetNodePoller(ctx, staleNode); err != nil || p.Claim != nil || len(p.Targets) != 0 { + t.Fatalf("stale poller: %+v %v", p, err) + } + // Once it sends a foreign claim it is foreign, no longer local, and the view follows the claim. + w.claimVia(local, foreignOtherBroker, 2, reqNode(pollKey(tgA), false, "ok")) + if got := flags(localNode); got != [3]bool{true, true, false} { + t.Fatalf("flags after a foreign claim: %v", got) + } + if p, err = s.GetNodePoller(ctx, localNode); err != nil || p.Claim == nil || !p.Claim.Foreign || len(p.Targets) != 1 || p.Targets[0].State != "ok" { + t.Fatalf("poller after a foreign claim: %+v %v", p, err) + } +} + func mustHex(t *testing.T, s string) []byte { t.Helper() b, err := hex.DecodeString(s) diff --git a/db/queries/polling.sql b/db/queries/polling.sql index 1376d733..68db3314 100644 --- a/db/queries/polling.sql +++ b/db/queries/polling.sql @@ -125,15 +125,36 @@ LEFT JOIN LATERAL ( WHERE fc.observer_public_key = $1 ORDER BY lower(NULLIF(n.name, '')) NULLS LAST, ft.target_public_key; +-- name: NodeLocalPollerTargets :many +-- The repeaters an observer with no claim sent foreign readings for since readings_after, each with its newest +-- reading from that observer, newest first. +SELECT t.target_public_key, n.id AS node_id, COALESCE(n.name, '')::text AS name, + lr.sampled_at::timestamptz AS latest_reading_at, lr.poll_rssi AS latest_reading_rssi, + COALESCE(lr.signed, false)::boolean AS latest_reading_signed +FROM ( + SELECT DISTINCT r.target_public_key FROM repeater_readings r + WHERE r.observer_public_key = sqlc.arg(observer_public_key) AND r.foreign_source AND r.received_at > sqlc.arg(readings_after) +) t +LEFT JOIN nodes n ON n.public_key = t.target_public_key +LEFT JOIN LATERAL ( + SELECT r.sampled_at, r.poll_rssi, r.signed FROM repeater_readings r + WHERE r.target_public_key = t.target_public_key AND r.observer_public_key = sqlc.arg(observer_public_key) + ORDER BY r.sampled_at DESC LIMIT 1 +) lr ON true +ORDER BY lr.sampled_at DESC NULLS LAST, t.target_public_key +LIMIT sqlc.arg(row_limit); + -- name: CountObserverReadings :one -- Readings the observer delivered since a time, and how many of them were stored as foreign. SELECT count(*)::int AS readings, count(*) FILTER (WHERE foreign_source)::int AS foreign_readings FROM repeater_readings WHERE observer_public_key = $1 AND received_at > $2; -- name: IsPollerKey :one --- A foreign claim counts: the observer polls, it only takes no orders from this server. +-- A foreign claim counts: the observer polls, it only takes no orders from this server. So do a day's foreign +-- readings from an observer that sends no claim. 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))::boolean; + 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: DeletePollingCandidates :exec DELETE FROM polling_candidates WHERE observer_public_key = $1; diff --git a/db/queries/queries.sql b/db/queries/queries.sql index 51be58ec..e524ad23 100644 --- a/db/queries/queries.sql +++ b/db/queries/queries.sql @@ -1367,8 +1367,10 @@ UPDATE nodes SET default_scope_id = $2 WHERE id = $1; -- name: GetNodeByID :one SELECT n.*, ts.name AS default_scope_name, EXISTS (SELECT 1 FROM observers o WHERE o.public_key = n.public_key) AS is_observer, - (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))::boolean AS is_poller, + (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_poller, EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AS is_foreign_poller, + -- Readings and no claim of either kind, as an observer in local mode sends. + (NOT EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) AND NOT EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AND EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_local_poller, (SELECT o.id FROM observers o WHERE o.public_key = n.public_key LIMIT 1) AS observer_id, (SELECT json_agg(json_build_object('iata', ni.iata, 'lastHeard', (extract(epoch from ni.last_heard) * 1000)::bigint) ORDER BY ni.last_heard DESC) FROM node_iatas ni WHERE ni.node_id = n.id) AS iatas, @@ -1422,8 +1424,8 @@ WHERE AND ($11::text = '' OR encode(n.public_key, 'hex') ILIKE $11 || '%') AND ( $13::text = 'any' - OR ($13::text = 'true' AND (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))) - OR ($13::text = 'false' AND NOT (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))) + OR ($13::text = 'true' AND (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))) + OR ($13::text = 'false' AND NOT (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))) ) ORDER BY n.last_seen DESC, n.id DESC LIMIT $8 @@ -1433,8 +1435,10 @@ SELECT n.id, n.public_key, n.node_type, n.name, n.latitude, n.longitude, n.last_ (SELECT json_agg(json_build_object('iata', ni.iata, 'lastHeard', (extract(epoch from ni.last_heard) * 1000)::bigint) ORDER BY ni.last_heard DESC) FROM node_iatas ni WHERE ni.node_id = n.id) AS iatas, EXISTS (SELECT 1 FROM observers o WHERE o.public_key = n.public_key) AS is_observer, - (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))::boolean AS is_poller, + (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_poller, EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AS is_foreign_poller, + -- Readings and no claim of either kind, as an observer in local mode sends. + (NOT EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) AND NOT EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AND EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_local_poller, (SELECT o.id FROM observers o WHERE o.public_key = n.public_key LIMIT 1) AS observer_id, (SELECT COUNT(DISTINCT nn.neighbor_id) FROM node_neighbors nn WHERE nn.node_id = n.id)::bigint AS known_neighbor_count, (CASE WHEN $10::bool THEN @@ -1485,8 +1489,8 @@ WHERE AND (@pubkey_prefix::text = '' OR encode(n.public_key, 'hex') ILIKE @pubkey_prefix::text || '%') AND ( @poller::text = 'any' - OR (@poller::text = 'true' AND (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))) - OR (@poller::text = 'false' AND NOT (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))) + OR (@poller::text = 'true' AND (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))) + OR (@poller::text = 'false' AND NOT (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))) ) ), page AS ( SELECT * FROM keyed @@ -1509,8 +1513,10 @@ SELECT n.id, n.public_key, n.node_type, n.name, n.latitude, n.longitude, n.last_ (SELECT json_agg(json_build_object('iata', ni.iata, 'lastHeard', (extract(epoch from ni.last_heard) * 1000)::bigint) ORDER BY ni.last_heard DESC) FROM node_iatas ni WHERE ni.node_id = n.id) AS iatas, EXISTS (SELECT 1 FROM observers o WHERE o.public_key = n.public_key) AS is_observer, - (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))::boolean AS is_poller, + (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_poller, EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AS is_foreign_poller, + -- Readings and no claim of either kind, as an observer in local mode sends. + (NOT EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) AND NOT EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AND EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_local_poller, (SELECT o.id FROM observers o WHERE o.public_key = n.public_key LIMIT 1) AS observer_id, (SELECT COUNT(DISTINCT nn.neighbor_id) FROM node_neighbors nn WHERE nn.node_id = n.id)::bigint AS known_neighbor_count, (CASE WHEN @include_neighbors::bool THEN diff --git a/db/sqlc/mock/querier.go b/db/sqlc/mock/querier.go index c43951ec..ff7aa551 100644 --- a/db/sqlc/mock/querier.go +++ b/db/sqlc/mock/querier.go @@ -4743,6 +4743,21 @@ func (mr *MockQuerierMockRecorder) NodeLatestTrustedReadingAt(ctx, targetPublicK return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NodeLatestTrustedReadingAt", reflect.TypeOf((*MockQuerier)(nil).NodeLatestTrustedReadingAt), ctx, targetPublicKey) } +// NodeLocalPollerTargets mocks base method. +func (m *MockQuerier) NodeLocalPollerTargets(ctx context.Context, arg db.NodeLocalPollerTargetsParams) ([]db.NodeLocalPollerTargetsRow, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "NodeLocalPollerTargets", ctx, arg) + ret0, _ := ret[0].([]db.NodeLocalPollerTargetsRow) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// NodeLocalPollerTargets indicates an expected call of NodeLocalPollerTargets. +func (mr *MockQuerierMockRecorder) NodeLocalPollerTargets(ctx, arg any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NodeLocalPollerTargets", reflect.TypeOf((*MockQuerier)(nil).NodeLocalPollerTargets), ctx, arg) +} + // NodePoller mocks base method. func (m *MockQuerier) NodePoller(ctx context.Context, arg db.NodePollerParams) ([]db.NodePollerRow, error) { m.ctrl.T.Helper() diff --git a/db/sqlc/polling.sql.go b/db/sqlc/polling.sql.go index f0cbfed7..7dcdc2f4 100644 --- a/db/sqlc/polling.sql.go +++ b/db/sqlc/polling.sql.go @@ -548,10 +548,12 @@ func (q *Queries) InsertRepeaterReading(ctx context.Context, arg InsertRepeaterR const isPollerKey = `-- name: IsPollerKey :one 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))::boolean + 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 ` -// A foreign claim counts: the observer polls, it only takes no orders from this server. +// A foreign claim counts: the observer polls, it only takes no orders from this server. So do a day's foreign +// readings from an observer that sends no claim. func (q *Queries) IsPollerKey(ctx context.Context, observerPublicKey []byte) (bool, error) { row := q.db.QueryRow(ctx, isPollerKey, observerPublicKey) var column_1 bool @@ -1361,6 +1363,68 @@ func (q *Queries) NodeLatestTrustedReadingAt(ctx context.Context, targetPublicKe return sampled_at, err } +const nodeLocalPollerTargets = `-- name: NodeLocalPollerTargets :many +SELECT t.target_public_key, n.id AS node_id, COALESCE(n.name, '')::text AS name, + lr.sampled_at::timestamptz AS latest_reading_at, lr.poll_rssi AS latest_reading_rssi, + COALESCE(lr.signed, false)::boolean AS latest_reading_signed +FROM ( + SELECT DISTINCT r.target_public_key FROM repeater_readings r + WHERE r.observer_public_key = $1 AND r.foreign_source AND r.received_at > $2 +) t +LEFT JOIN nodes n ON n.public_key = t.target_public_key +LEFT JOIN LATERAL ( + SELECT r.sampled_at, r.poll_rssi, r.signed FROM repeater_readings r + WHERE r.target_public_key = t.target_public_key AND r.observer_public_key = $1 + ORDER BY r.sampled_at DESC LIMIT 1 +) lr ON true +ORDER BY lr.sampled_at DESC NULLS LAST, t.target_public_key +LIMIT $3 +` + +type NodeLocalPollerTargetsParams struct { + ObserverPublicKey []byte `json:"observer_public_key"` + ReadingsAfter pgtype.Timestamptz `json:"readings_after"` + RowLimit int32 `json:"row_limit"` +} + +type NodeLocalPollerTargetsRow struct { + TargetPublicKey []byte `json:"target_public_key"` + NodeID pgtype.UUID `json:"node_id"` + Name string `json:"name"` + LatestReadingAt pgtype.Timestamptz `json:"latest_reading_at"` + LatestReadingRssi *int16 `json:"latest_reading_rssi"` + LatestReadingSigned bool `json:"latest_reading_signed"` +} + +// The repeaters an observer with no claim sent foreign readings for since readings_after, each with its newest +// reading from that observer, newest first. +func (q *Queries) NodeLocalPollerTargets(ctx context.Context, arg NodeLocalPollerTargetsParams) ([]NodeLocalPollerTargetsRow, error) { + rows, err := q.db.Query(ctx, nodeLocalPollerTargets, arg.ObserverPublicKey, arg.ReadingsAfter, arg.RowLimit) + if err != nil { + return nil, err + } + defer rows.Close() + items := []NodeLocalPollerTargetsRow{} + for rows.Next() { + var i NodeLocalPollerTargetsRow + if err := rows.Scan( + &i.TargetPublicKey, + &i.NodeID, + &i.Name, + &i.LatestReadingAt, + &i.LatestReadingRssi, + &i.LatestReadingSigned, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const nodePoller = `-- name: NodePoller :many WITH cl AS MATERIALIZED ( SELECT p.observer_public_key, p.received_at, p.accepts_requests, p.request_slots::int AS request_slots, diff --git a/db/sqlc/querier.go b/db/sqlc/querier.go index b8e246ee..96bb9387 100644 --- a/db/sqlc/querier.go +++ b/db/sqlc/querier.go @@ -417,7 +417,8 @@ type Querier interface { InsertUserAtlasPin(ctx context.Context, arg InsertUserAtlasPinParams) error // An observer that sent status since status_after, as in RequestNode. IsObserverKey(ctx context.Context, arg IsObserverKeyParams) (bool, error) - // A foreign claim counts: the observer polls, it only takes no orders from this server. + // A foreign claim counts: the observer polls, it only takes no orders from this server. So do a day's foreign + // readings from an observer that sends no claim. IsPollerKey(ctx context.Context, observerPublicKey []byte) (bool, error) // Newest trusted battery and temperature per polled node since a time, driven by polled targets, not all nodes. // The received_at bound lets the BRIN index prune the history scan for readings of unassigned targets. @@ -726,6 +727,9 @@ type Querier interface { NodeHasReadings(ctx context.Context, targetPublicKey []byte) (bool, error) NodeIDsByKeys(ctx context.Context, dollar_1 [][]byte) ([]NodeIDsByKeysRow, error) NodeLatestTrustedReadingAt(ctx context.Context, targetPublicKey []byte) (pgtype.Timestamptz, error) + // The repeaters an observer with no claim sent foreign readings for since readings_after, each with its newest + // reading from that observer, newest first. + NodeLocalPollerTargets(ctx context.Context, arg NodeLocalPollerTargetsParams) ([]NodeLocalPollerTargetsRow, error) // The observer's stored claim, live or expired, and the targets it names, in one statement so they come from one // snapshot. No claim gives no rows; a claim that names nothing gives one row with a NULL target. readings is how // many readings the observer delivered since readings_after. pending_seats counts the requested targets it has diff --git a/db/sqlc/queries.sql.go b/db/sqlc/queries.sql.go index e299b83f..b3227b15 100644 --- a/db/sqlc/queries.sql.go +++ b/db/sqlc/queries.sql.go @@ -881,8 +881,10 @@ func (q *Queries) GetNodeActivityHourly(ctx context.Context, arg GetNodeActivity const getNodeByID = `-- name: GetNodeByID :one SELECT n.id, n.public_key, n.node_type, n.name, n.latitude, n.longitude, n.location_source, n.last_advert_at, n.supports_multibyte_paths, n.supports_multibyte_traces, n.default_scope_id, n.min_firmware_version, n.first_seen, n.last_seen, n.radio_freq_mhz, n.radio_sf, n.radio_bw_khz, n.metadata, n.device_clock_drift_seconds, n.prev_clock_drift_seconds, ts.name AS default_scope_name, EXISTS (SELECT 1 FROM observers o WHERE o.public_key = n.public_key) AS is_observer, - (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))::boolean AS is_poller, + (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_poller, EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AS is_foreign_poller, + -- Readings and no claim of either kind, as an observer in local mode sends. + (NOT EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) AND NOT EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AND EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_local_poller, (SELECT o.id FROM observers o WHERE o.public_key = n.public_key LIMIT 1) AS observer_id, (SELECT json_agg(json_build_object('iata', ni.iata, 'lastHeard', (extract(epoch from ni.last_heard) * 1000)::bigint) ORDER BY ni.last_heard DESC) FROM node_iatas ni WHERE ni.node_id = n.id) AS iatas, @@ -922,6 +924,7 @@ type GetNodeByIDRow struct { IsObserver bool `json:"is_observer"` IsPoller bool `json:"is_poller"` IsForeignPoller bool `json:"is_foreign_poller"` + IsLocalPoller bool `json:"is_local_poller"` ObserverID uuid.UUID `json:"observer_id"` Iatas []byte `json:"iatas"` KnownNeighborCount int64 `json:"known_neighbor_count"` @@ -956,6 +959,7 @@ func (q *Queries) GetNodeByID(ctx context.Context, id uuid.UUID) (GetNodeByIDRow &i.IsObserver, &i.IsPoller, &i.IsForeignPoller, + &i.IsLocalPoller, &i.ObserverID, &i.Iatas, &i.KnownNeighborCount, @@ -4421,8 +4425,8 @@ WHERE AND ($11::text = '' OR encode(n.public_key, 'hex') ILIKE $11 || '%') AND ( $13::text = 'any' - OR ($13::text = 'true' AND (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))) - OR ($13::text = 'false' AND NOT (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))) + OR ($13::text = 'true' AND (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))) + OR ($13::text = 'false' AND NOT (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))) ) ORDER BY n.last_seen DESC, n.id DESC LIMIT $8 @@ -4432,8 +4436,10 @@ SELECT n.id, n.public_key, n.node_type, n.name, n.latitude, n.longitude, n.last_ (SELECT json_agg(json_build_object('iata', ni.iata, 'lastHeard', (extract(epoch from ni.last_heard) * 1000)::bigint) ORDER BY ni.last_heard DESC) FROM node_iatas ni WHERE ni.node_id = n.id) AS iatas, EXISTS (SELECT 1 FROM observers o WHERE o.public_key = n.public_key) AS is_observer, - (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))::boolean AS is_poller, + (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_poller, EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AS is_foreign_poller, + -- Readings and no claim of either kind, as an observer in local mode sends. + (NOT EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) AND NOT EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AND EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_local_poller, (SELECT o.id FROM observers o WHERE o.public_key = n.public_key LIMIT 1) AS observer_id, (SELECT COUNT(DISTINCT nn.neighbor_id) FROM node_neighbors nn WHERE nn.node_id = n.id)::bigint AS known_neighbor_count, (CASE WHEN $10::bool THEN @@ -4475,6 +4481,7 @@ type ListNodesRow struct { IsObserver bool `json:"is_observer"` IsPoller bool `json:"is_poller"` IsForeignPoller bool `json:"is_foreign_poller"` + IsLocalPoller bool `json:"is_local_poller"` ObserverID uuid.UUID `json:"observer_id"` KnownNeighborCount int64 `json:"known_neighbor_count"` NeighborIds []uuid.UUID `json:"neighbor_ids"` @@ -4520,6 +4527,7 @@ func (q *Queries) ListNodes(ctx context.Context, arg ListNodesParams) ([]ListNod &i.IsObserver, &i.IsPoller, &i.IsForeignPoller, + &i.IsLocalPoller, &i.ObserverID, &i.KnownNeighborCount, &i.NeighborIds, @@ -4574,8 +4582,8 @@ WHERE AND ($11::text = '' OR encode(n.public_key, 'hex') ILIKE $11::text || '%') AND ( $12::text = 'any' - OR ($12::text = 'true' AND (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))) - OR ($12::text = 'false' AND NOT (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))) + OR ($12::text = 'true' AND (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))) + OR ($12::text = 'false' AND NOT (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))) ) ), page AS ( SELECT id, public_key, node_type, name, latitude, longitude, last_seen, radio_freq_mhz, radio_sf, radio_bw_khz, default_scope_name, k_null, k_text, k_num, k_seen FROM keyed @@ -4598,8 +4606,10 @@ SELECT n.id, n.public_key, n.node_type, n.name, n.latitude, n.longitude, n.last_ (SELECT json_agg(json_build_object('iata', ni.iata, 'lastHeard', (extract(epoch from ni.last_heard) * 1000)::bigint) ORDER BY ni.last_heard DESC) FROM node_iatas ni WHERE ni.node_id = n.id) AS iatas, EXISTS (SELECT 1 FROM observers o WHERE o.public_key = n.public_key) AS is_observer, - (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key))::boolean AS is_poller, + (EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) OR EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_poller, EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AS is_foreign_poller, + -- Readings and no claim of either kind, as an observer in local mode sends. + (NOT EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = n.public_key) AND NOT EXISTS (SELECT 1 FROM polling_foreign_claims fc WHERE fc.observer_public_key = n.public_key) AND EXISTS (SELECT 1 FROM repeater_readings lr WHERE lr.observer_public_key = n.public_key AND lr.foreign_source AND lr.received_at > now() - interval '24 hours'))::boolean AS is_local_poller, (SELECT o.id FROM observers o WHERE o.public_key = n.public_key LIMIT 1) AS observer_id, (SELECT COUNT(DISTINCT nn.neighbor_id) FROM node_neighbors nn WHERE nn.node_id = n.id)::bigint AS known_neighbor_count, (CASE WHEN $1::bool THEN @@ -4654,6 +4664,7 @@ type ListNodesSortedRow struct { IsObserver bool `json:"is_observer"` IsPoller bool `json:"is_poller"` IsForeignPoller bool `json:"is_foreign_poller"` + IsLocalPoller bool `json:"is_local_poller"` ObserverID uuid.UUID `json:"observer_id"` KnownNeighborCount int64 `json:"known_neighbor_count"` NeighborIds []uuid.UUID `json:"neighbor_ids"` @@ -4710,6 +4721,7 @@ func (q *Queries) ListNodesSorted(ctx context.Context, arg ListNodesSortedParams &i.IsObserver, &i.IsPoller, &i.IsForeignPoller, + &i.IsLocalPoller, &i.ObserverID, &i.KnownNeighborCount, &i.NeighborIds, diff --git a/docs/docs.go b/docs/docs.go index c3f98da3..81a74a18 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -4665,7 +4665,7 @@ const docTemplate = `{ }, { "type": "boolean", - "description": "Filter by poller role (true/false); omit for no filter", + "description": "Filter by poller role, local pollers included (true/false); omit for no filter", "name": "poller", "in": "query" }, @@ -5031,7 +5031,7 @@ const docTemplate = `{ }, "/nodes/{nodeId}/poller": { "get": { - "description": "For a node that is an observer with a polling claim: its newest claim with slot usage, the readings it delivered in the last 24 hours, and one row per repeater the claim names, assigned ones first by rank. An expired claim is still returned with live false while it is stored. claim is null and targets is empty when the node has no claim or polling is off.", + "description": "For a node that is an observer with a polling claim: its newest claim with slot usage, the readings it delivered in the last 24 hours, and one row per repeater the claim names, assigned ones first by rank. An expired claim is still returned with live false while it is stored. claim is null when the node has no claim or polling is off; targets is then empty, unless the observer sent readings without a claim in the last 24 hours (a local poller), in which case it lists up to 32 repeaters those readings were for, newest reading first, all unassigned.", "produces": [ "application/json" ], @@ -9078,12 +9078,16 @@ const docTemplate = `{ "description": "true if that claim is foreign: the observer polls but follows another server, or none", "type": "boolean" }, + "isLocalPoller": { + "description": "true if the observer sent readings in the last day and no claim, as the firmware's local mode does", + "type": "boolean" + }, "isObserver": { "description": "true if this node is also a known observer", "type": "boolean" }, "isPoller": { - "description": "true if this node is an observer with a polling claim, this server's own or a foreign one", + "description": "true if this node is an observer that polls: one with a claim, this server's own or foreign, or a local poller", "type": "boolean" }, "knownNeighborCount": { @@ -9634,12 +9638,16 @@ const docTemplate = `{ "description": "true if that claim is foreign: the observer polls but follows another server, or none", "type": "boolean" }, + "isLocalPoller": { + "description": "true if the observer sent readings in the last day and no claim, as the firmware's local mode does", + "type": "boolean" + }, "isObserver": { "description": "true if this node is also a known observer", "type": "boolean" }, "isPoller": { - "description": "true if this node is an observer with a polling claim, this server's own or a foreign one", + "description": "true if this node is an observer that polls: one with a claim, this server's own or foreign, or a local poller", "type": "boolean" }, "knownNeighborCount": { @@ -12277,7 +12285,7 @@ const docTemplate = `{ // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = &swag.Spec{ - Version: "2.3.2", + Version: "2.3.3", Host: "localhost:8080", BasePath: "/api/v1", Schemes: []string{"http", "https"}, diff --git a/docs/swagger.json b/docs/swagger.json index e05d9e75..c80248a3 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -15,7 +15,7 @@ "license": { "name": "AGPL-3-or-later" }, - "version": "2.3.2" + "version": "2.3.3" }, "host": "localhost:8080", "basePath": "/api/v1", @@ -4663,7 +4663,7 @@ }, { "type": "boolean", - "description": "Filter by poller role (true/false); omit for no filter", + "description": "Filter by poller role, local pollers included (true/false); omit for no filter", "name": "poller", "in": "query" }, @@ -5029,7 +5029,7 @@ }, "/nodes/{nodeId}/poller": { "get": { - "description": "For a node that is an observer with a polling claim: its newest claim with slot usage, the readings it delivered in the last 24 hours, and one row per repeater the claim names, assigned ones first by rank. An expired claim is still returned with live false while it is stored. claim is null and targets is empty when the node has no claim or polling is off.", + "description": "For a node that is an observer with a polling claim: its newest claim with slot usage, the readings it delivered in the last 24 hours, and one row per repeater the claim names, assigned ones first by rank. An expired claim is still returned with live false while it is stored. claim is null when the node has no claim or polling is off; targets is then empty, unless the observer sent readings without a claim in the last 24 hours (a local poller), in which case it lists up to 32 repeaters those readings were for, newest reading first, all unassigned.", "produces": [ "application/json" ], @@ -9076,12 +9076,16 @@ "description": "true if that claim is foreign: the observer polls but follows another server, or none", "type": "boolean" }, + "isLocalPoller": { + "description": "true if the observer sent readings in the last day and no claim, as the firmware's local mode does", + "type": "boolean" + }, "isObserver": { "description": "true if this node is also a known observer", "type": "boolean" }, "isPoller": { - "description": "true if this node is an observer with a polling claim, this server's own or a foreign one", + "description": "true if this node is an observer that polls: one with a claim, this server's own or foreign, or a local poller", "type": "boolean" }, "knownNeighborCount": { @@ -9632,12 +9636,16 @@ "description": "true if that claim is foreign: the observer polls but follows another server, or none", "type": "boolean" }, + "isLocalPoller": { + "description": "true if the observer sent readings in the last day and no claim, as the firmware's local mode does", + "type": "boolean" + }, "isObserver": { "description": "true if this node is also a known observer", "type": "boolean" }, "isPoller": { - "description": "true if this node is an observer with a polling claim, this server's own or a foreign one", + "description": "true if this node is an observer that polls: one with a claim, this server's own or foreign, or a local poller", "type": "boolean" }, "knownNeighborCount": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index ba0313f9..56b22d93 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -981,12 +981,16 @@ definitions: description: 'true if that claim is foreign: the observer polls but follows another server, or none' type: boolean + isLocalPoller: + description: true if the observer sent readings in the last day and no claim, + as the firmware's local mode does + type: boolean isObserver: description: true if this node is also a known observer type: boolean isPoller: - description: true if this node is an observer with a polling claim, this server's - own or a foreign one + description: 'true if this node is an observer that polls: one with a claim, + this server''s own or foreign, or a local poller' type: boolean knownNeighborCount: type: integer @@ -1396,12 +1400,16 @@ definitions: description: 'true if that claim is foreign: the observer polls but follows another server, or none' type: boolean + isLocalPoller: + description: true if the observer sent readings in the last day and no claim, + as the firmware's local mode does + type: boolean isObserver: description: true if this node is also a known observer type: boolean isPoller: - description: true if this node is an observer with a polling claim, this server's - own or a foreign one + description: 'true if this node is an observer that polls: one with a claim, + this server''s own or foreign, or a local poller' type: boolean knownNeighborCount: type: integer @@ -3226,7 +3234,7 @@ info: name: AGPL-3-or-later termsOfService: https://github.com/MeshCore-Beacon/beacon-server title: MeshCore Beacon API - version: 2.3.2 + version: 2.3.3 paths: /admin/accounts: get: @@ -6352,7 +6360,8 @@ paths: in: query name: supportsMultibyteTraces type: boolean - - description: Filter by poller role (true/false); omit for no filter + - description: Filter by poller role, local pollers included (true/false); omit + for no filter in: query name: poller type: boolean @@ -6573,7 +6582,10 @@ paths: claim with slot usage, the readings it delivered in the last 24 hours, and one row per repeater the claim names, assigned ones first by rank. An expired claim is still returned with live false while it is stored. claim is null - and targets is empty when the node has no claim or polling is off.' + when the node has no claim or polling is off; targets is then empty, unless + the observer sent readings without a claim in the last 24 hours (a local poller), + in which case it lists up to 32 repeaters those readings were for, newest + reading first, all unassigned.' parameters: - description: Node UUID in: path diff --git a/internal/api/handlers/node_poller_test.go b/internal/api/handlers/node_poller_test.go index 96d9615f..2bca0925 100644 --- a/internal/api/handlers/node_poller_test.go +++ b/internal/api/handlers/node_poller_test.go @@ -72,6 +72,27 @@ func TestGetNodePoller_NotAPoller(t *testing.T) { } } +func TestGetNodePoller_LocalShape(t *testing.T) { + node := uuid.New() + at := int64(1795799000000) + name := "Ridge" + rssi := -91 + key := strings.Repeat("0a", 32) + sr := stubReader{getNodePoller: func(context.Context, uuid.UUID) (*api.NodePoller, error) { + return &api.NodePoller{Readings24h: 4, ForeignReadings24h: 4, Targets: []api.NodePollerTarget{ + {NodeID: &node, PublicKey: key, Name: &name, Role: "unassigned", LatestReadingAt: &at, LatestReadingRssi: &rssi}, + }}, nil + }} + w := nodePollerGet(t, sr, uuid.NewString()) + want := `{"claim":null,"readings24h":4,"foreignReadings24h":4,"targets":[` + + `{"nodeId":"` + node.String() + `","publicKey":"` + key + `","name":"Ridge","requested":false,"role":"unassigned","rank":null,` + + `"state":"","misses":0,"lastAttempt":null,"lastOk":null,"claimedSnr":null,"evidenceSnr":null,` + + `"evidenceCount":0,"latestReadingAt":1795799000000,"latestReadingRssi":-91,"latestReadingSigned":false}]}` + if w.Code != http.StatusOK || strings.TrimSpace(w.Body.String()) != want { + t.Fatalf("%d %s\nwant %s", w.Code, w.Body, want) + } +} + func TestGetNodePoller_NilTargetsMarshalAsEmpty(t *testing.T) { sr := stubReader{getNodePoller: func(context.Context, uuid.UUID) (*api.NodePoller, error) { return &api.NodePoller{Claim: &api.NodePollerClaim{}}, nil diff --git a/internal/api/handlers/nodes.go b/internal/api/handlers/nodes.go index 1ea78755..db27f3bd 100644 --- a/internal/api/handlers/nodes.go +++ b/internal/api/handlers/nodes.go @@ -143,7 +143,7 @@ func listLatestNodeReadings(reader api.Reader) http.HandlerFunc { // @Param pubkeyPrefix query string false "Partial public key match: hex prefix, case-insensitive" // @Param supportsMultibytePaths query bool false "Filter by multibyte path support (true/false); omit for no filter" // @Param supportsMultibyteTraces query bool false "Filter by multibyte trace support (true/false); omit for no filter" -// @Param poller query bool false "Filter by poller role (true/false); omit for no filter" +// @Param poller query bool false "Filter by poller role, local pollers included (true/false); omit for no filter" // @Param neighbors query bool false "Include each node's known neighbor IDs (neighborIds field). Bare ?neighbors or ?neighbors=true enables it; omit/false for none" // @Param cursor query int false "last_seen epoch ms of last item for pagination" // @Param pageCursor query string false "Opaque nextPageCursor from a previous response; keeps millisecond ties. Wins over cursor when both are sent" @@ -592,7 +592,7 @@ func getNodePolling(reader api.Reader) http.HandlerFunc { // getNodePoller godoc // // @Summary Get what a node polls -// @Description For a node that is an observer with a polling claim: its newest claim with slot usage, the readings it delivered in the last 24 hours, and one row per repeater the claim names, assigned ones first by rank. An expired claim is still returned with live false while it is stored. claim is null and targets is empty when the node has no claim or polling is off. +// @Description For a node that is an observer with a polling claim: its newest claim with slot usage, the readings it delivered in the last 24 hours, and one row per repeater the claim names, assigned ones first by rank. An expired claim is still returned with live false while it is stored. claim is null when the node has no claim or polling is off; targets is then empty, unless the observer sent readings without a claim in the last 24 hours (a local poller), in which case it lists up to 32 repeaters those readings were for, newest reading first, all unassigned. // @Tags Nodes // @Produce json // @Param nodeId path string true "Node UUID" diff --git a/internal/api/handlers/nodes_test.go b/internal/api/handlers/nodes_test.go index 36337cb4..279d6a7e 100644 --- a/internal/api/handlers/nodes_test.go +++ b/internal/api/handlers/nodes_test.go @@ -787,6 +787,20 @@ func TestNodesRouter_TelemetryPathsUnchanged(t *testing.T) { } } +func TestGetNode_PollerFlags(t *testing.T) { + r := chi.NewRouter() + r.Get("/nodes/{nodeId}", getNode(stubReader{ + getNode: func(_ context.Context, id uuid.UUID) (*api.Node, error) { + return &api.Node{NodeSummary: api.NodeSummary{ID: id, IsPoller: true, IsLocalPoller: true}}, nil + }, + })) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/nodes/"+uuid.NewString(), nil)) + if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, `"isPoller":true,"isForeignPoller":false,"isLocalPoller":true`) { + t.Errorf("%d %s", w.Code, body) + } +} + func TestListNodes_PollerParam(t *testing.T) { yes, no := true, false for _, tc := range []struct { diff --git a/internal/api/node_telemetry.go b/internal/api/node_telemetry.go index 2b3fdc83..0ea6cad4 100644 --- a/internal/api/node_telemetry.go +++ b/internal/api/node_telemetry.go @@ -360,7 +360,7 @@ type NodePollerClaim struct { Slots NodePollerSlots `json:"slots"` } -// NodePollerTarget is one repeater a poller's claim names. Role is poller (rank 0), standby (rank 1+) or +// NodePollerTarget is one repeater a poller's claim names, or one a claimless observer sent readings for. Role is poller (rank 0), standby (rank 1+) or // unassigned (rank null). State is the device's own word for the target, passed through as stored. type NodePollerTarget struct { NodeID *uuid.UUID `json:"nodeId"` // null when the target has no node row @@ -384,7 +384,8 @@ type NodePollerTarget struct { LatestReadingSigned bool `json:"latestReadingSigned"` } -// NodePoller is what a node polls as an observer. Claim is null when the node has no polling claim. +// NodePoller is what a node polls as an observer. Claim is null when the node has no polling claim; Targets then +// holds the repeaters its claimless readings of the last 24 h were for, if any. type NodePoller struct { Claim *NodePollerClaim `json:"claim"` Readings24h int `json:"readings24h"` // readings it delivered in the last 24 h diff --git a/internal/api/nodes.go b/internal/api/nodes.go index da542a94..fa8e73f0 100644 --- a/internal/api/nodes.go +++ b/internal/api/nodes.go @@ -109,8 +109,9 @@ type NodeSummary struct { NodeTypeName string `json:"nodeTypeName"` Name *string `json:"name,omitempty"` IsObserver bool `json:"isObserver"` // true if this node is also a known observer - IsPoller bool `json:"isPoller"` // true if this node is an observer with a polling claim, this server's own or a foreign one + IsPoller bool `json:"isPoller"` // true if this node is an observer that polls: one with a claim, this server's own or foreign, or a local poller IsForeignPoller bool `json:"isForeignPoller"` // true if that claim is foreign: the observer polls but follows another server, or none + IsLocalPoller bool `json:"isLocalPoller"` // true if the observer sent readings in the last day and no claim, as the firmware's local mode does ObserverID *uuid.UUID `json:"observerId,omitempty"` // UUID of the associated observer row, if any Latitude *float64 `json:"lat,omitempty"` // decimal degrees, from advert AppData Longitude *float64 `json:"lng,omitempty"` // decimal degrees, from advert AppData diff --git a/internal/ingest/ingest.go b/internal/ingest/ingest.go index 040d9ab6..167f84f1 100644 --- a/internal/ingest/ingest.go +++ b/internal/ingest/ingest.go @@ -165,7 +165,7 @@ type DB interface { // 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 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 // GetObserverScopes returns the list of scope names associated with the given observer.