Files
beacon-server/db/sqlc/polling.sql.go
T
MrAlders0n a7c36e8e76 feat(polling): decode sensor channels from LPP and serve them with node telemetry
Humidity, pressure, gas and power monitor channels are decoded when a reading is stored. Positions and altitude are never decoded. Fixes the humidity size, which is one byte on the wire.
2026-11-29 21:09:23 -05:00

2102 lines
81 KiB
Go

// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: polling.sql
package db
import (
"context"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
)
const compactTargetAssignments = `-- name: CompactTargetAssignments :exec
UPDATE polling_assignments a SET rank = r.new_rank
FROM (
SELECT observer_public_key, (row_number() OVER (ORDER BY rank, observer_public_key) - 1)::smallint AS new_rank
FROM polling_assignments WHERE target_public_key = $1
) r
WHERE a.target_public_key = $1 AND a.observer_public_key = r.observer_public_key AND a.rank <> r.new_rank
`
// Renumbers the target's ranks 0..n-1 in their current order, so after a delete the best survivor polls. Only the
// lowest rank can become 0, so the one-poller index holds row by row. Run under LockPollingTarget.
func (q *Queries) CompactTargetAssignments(ctx context.Context, targetPublicKey []byte) error {
_, err := q.db.Exec(ctx, compactTargetAssignments, targetPublicKey)
return err
}
const corroborateReadings = `-- name: CorroborateReadings :execrows
WITH todo AS (
SELECT x.id, x.packet_hash, x.observer_id, x.sampled_at FROM repeater_readings x
WHERE x.packet_hash IS NOT NULL AND x.received_at >= $1
ORDER BY x.corroborated IS NOT NULL, CASE WHEN x.corroborated IS NULL THEN x.id ELSE -x.id END LIMIT $2
)
UPDATE repeater_readings r SET corroborated = (
SELECT count(DISTINCT po.observer_id) FROM packet_observations po
JOIN packets p ON p.packet_hash = po.packet_hash
WHERE po.packet_hash = t.packet_hash AND po.observer_id IS DISTINCT FROM t.observer_id
AND p.payload_type IN (1, 8)
AND po.heard_at BETWEEN t.sampled_at - interval '10 minutes' AND t.sampled_at + interval '10 minutes'
)::smallint
FROM todo t WHERE r.id = t.id
`
type CorroborateReadingsParams struct {
ReceivedAt pgtype.Timestamptz `json:"received_at"`
Limit int32 `json:"limit"`
}
// Recomputed each pass. Counts other observers that heard a RESPONSE (1) or PATH (8) packet with the reading's
// 8-byte hash within 10 minutes of sampled_at. packets and packet_observations keep no source hash, so the
// sender is not checked; packet_observations.payload_type is not always filled, so the type comes from packets.
// A reading whose observer row was deleted counts every observer. Never-counted readings go first, oldest first,
// then counted ones newest first, so every reading is reached however many arrive.
func (q *Queries) CorroborateReadings(ctx context.Context, arg CorroborateReadingsParams) (int64, error) {
result, err := q.db.Exec(ctx, corroborateReadings, arg.ReceivedAt, arg.Limit)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const countObserverReadings = `-- name: CountObserverReadings :one
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
`
type CountObserverReadingsParams struct {
ObserverPublicKey []byte `json:"observer_public_key"`
ReceivedAt pgtype.Timestamptz `json:"received_at"`
}
type CountObserverReadingsRow struct {
Readings int32 `json:"readings"`
ForeignReadings int32 `json:"foreign_readings"`
}
// Readings the observer delivered since a time, and how many of them were stored as foreign.
func (q *Queries) CountObserverReadings(ctx context.Context, arg CountObserverReadingsParams) (CountObserverReadingsRow, error) {
row := q.db.QueryRow(ctx, countObserverReadings, arg.ObserverPublicKey, arg.ReceivedAt)
var i CountObserverReadingsRow
err := row.Scan(&i.Readings, &i.ForeignReadings)
return i, err
}
const countTargetAssignments = `-- name: CountTargetAssignments :one
SELECT count(*)::int FROM polling_assignments WHERE target_public_key = $1
`
func (q *Queries) CountTargetAssignments(ctx context.Context, targetPublicKey []byte) (int32, error) {
row := q.db.QueryRow(ctx, countTargetAssignments, targetPublicKey)
var column_1 int32
err := row.Scan(&column_1)
return column_1, err
}
const countUntrustedNodeReadings = `-- name: CountUntrustedNodeReadings :one
SELECT count(*)::int FROM repeater_readings
WHERE target_public_key = $1
AND sampled_at >= $2::timestamptz
AND ($3::timestamptz IS NULL OR sampled_at < $3::timestamptz)
AND NOT trusted
`
type CountUntrustedNodeReadingsParams struct {
TargetPublicKey []byte `json:"target_public_key"`
Since pgtype.Timestamptz `json:"since"`
Until pgtype.Timestamptz `json:"until"`
}
func (q *Queries) CountUntrustedNodeReadings(ctx context.Context, arg CountUntrustedNodeReadingsParams) (int32, error) {
row := q.db.QueryRow(ctx, countUntrustedNodeReadings, arg.TargetPublicKey, arg.Since, arg.Until)
var column_1 int32
err := row.Scan(&column_1)
return column_1, err
}
const currentPollingPoller = `-- name: CurrentPollingPoller :one
SELECT observer_public_key FROM polling_assignments WHERE target_public_key = $1 AND rank = 0
`
func (q *Queries) CurrentPollingPoller(ctx context.Context, targetPublicKey []byte) ([]byte, error) {
row := q.db.QueryRow(ctx, currentPollingPoller, targetPublicKey)
var observer_public_key []byte
err := row.Scan(&observer_public_key)
return observer_public_key, err
}
const deleteExpiredForeignClaims = `-- name: DeleteExpiredForeignClaims :exec
DELETE FROM polling_foreign_claims WHERE received_at < $1
`
func (q *Queries) DeleteExpiredForeignClaims(ctx context.Context, receivedAt pgtype.Timestamptz) error {
_, err := q.db.Exec(ctx, deleteExpiredForeignClaims, receivedAt)
return err
}
const deleteExpiredPollingClaims = `-- name: DeleteExpiredPollingClaims :exec
DELETE FROM polling_claims WHERE received_at < $1
`
func (q *Queries) DeleteExpiredPollingClaims(ctx context.Context, receivedAt pgtype.Timestamptz) error {
_, err := q.db.Exec(ctx, deleteExpiredPollingClaims, receivedAt)
return err
}
const deleteExpiredRepeaterReadings = `-- name: DeleteExpiredRepeaterReadings :exec
DELETE FROM repeater_readings WHERE received_at < $1
`
func (q *Queries) DeleteExpiredRepeaterReadings(ctx context.Context, receivedAt pgtype.Timestamptz) error {
_, err := q.db.Exec(ctx, deleteExpiredRepeaterReadings, receivedAt)
return err
}
const deleteForeignClaim = `-- name: DeleteForeignClaim :execrows
DELETE FROM polling_foreign_claims WHERE observer_public_key = $1
`
func (q *Queries) DeleteForeignClaim(ctx context.Context, observerPublicKey []byte) (int64, error) {
result, err := q.db.Exec(ctx, deleteForeignClaim, observerPublicKey)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const deleteForeignTargets = `-- name: DeleteForeignTargets :exec
DELETE FROM polling_foreign_targets WHERE observer_public_key = $1
`
func (q *Queries) DeleteForeignTargets(ctx context.Context, observerPublicKey []byte) error {
_, err := q.db.Exec(ctx, deleteForeignTargets, observerPublicKey)
return err
}
const deleteObserverTargetAssignment = `-- name: DeleteObserverTargetAssignment :execrows
DELETE FROM polling_assignments WHERE target_public_key = $1 AND observer_public_key = $2
`
type DeleteObserverTargetAssignmentParams struct {
TargetPublicKey []byte `json:"target_public_key"`
ObserverPublicKey []byte `json:"observer_public_key"`
}
// Run under LockPollingTarget, then CompactTargetAssignments.
func (q *Queries) DeleteObserverTargetAssignment(ctx context.Context, arg DeleteObserverTargetAssignmentParams) (int64, error) {
result, err := q.db.Exec(ctx, deleteObserverTargetAssignment, arg.TargetPublicKey, arg.ObserverPublicKey)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const deleteOrphanPollingAssignments = `-- name: DeleteOrphanPollingAssignments :exec
DELETE FROM polling_assignments a
WHERE a.target_public_key = $1 AND NOT EXISTS (
SELECT 1 FROM polling_candidates c
WHERE c.target_public_key = a.target_public_key AND c.observer_public_key = a.observer_public_key
) AND NOT (a.requested AND EXISTS (
SELECT 1 FROM polling_claims cl WHERE cl.observer_public_key = a.observer_public_key AND cl.accepts_requests
))
`
// Run under LockPollingTarget, so it cannot interleave with an election of the target.
func (q *Queries) DeleteOrphanPollingAssignments(ctx context.Context, targetPublicKey []byte) error {
_, err := q.db.Exec(ctx, deleteOrphanPollingAssignments, targetPublicKey)
return err
}
const deletePollingAssignments = `-- name: DeletePollingAssignments :exec
DELETE FROM polling_assignments WHERE target_public_key = $1
`
func (q *Queries) DeletePollingAssignments(ctx context.Context, targetPublicKey []byte) error {
_, err := q.db.Exec(ctx, deletePollingAssignments, targetPublicKey)
return err
}
const deletePollingCandidates = `-- name: DeletePollingCandidates :exec
DELETE FROM polling_candidates WHERE observer_public_key = $1
`
func (q *Queries) DeletePollingCandidates(ctx context.Context, observerPublicKey []byte) error {
_, err := q.db.Exec(ctx, deletePollingCandidates, observerPublicKey)
return err
}
const deletePollingClaim = `-- name: DeletePollingClaim :execrows
DELETE FROM polling_claims WHERE observer_public_key = $1
`
// The observer's own claim and, by cascade, its candidates. Run under LockPollingSeats.
func (q *Queries) DeletePollingClaim(ctx context.Context, observerPublicKey []byte) (int64, error) {
result, err := q.db.Exec(ctx, deletePollingClaim, observerPublicKey)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const deleteUnplacedPollingClaims = `-- name: DeleteUnplacedPollingClaims :execrows
DELETE FROM polling_claims WHERE claim_policy <> $1
`
// The claims that were not taken as this server's own under the settings now in force. Their assignments are
// cleared by the next election pass.
func (q *Queries) DeleteUnplacedPollingClaims(ctx context.Context, claimPolicy string) (int64, error) {
result, err := q.db.Exec(ctx, deleteUnplacedPollingClaims, claimPolicy)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getPollingState = `-- name: GetPollingState :one
SELECT paused, paused_until, excluded_nodes FROM polling_state WHERE id
`
type GetPollingStateRow struct {
Paused bool `json:"paused"`
PausedUntil pgtype.Timestamptz `json:"paused_until"`
ExcludedNodes [][]byte `json:"excluded_nodes"`
}
func (q *Queries) GetPollingState(ctx context.Context) (GetPollingStateRow, error) {
row := q.db.QueryRow(ctx, getPollingState)
var i GetPollingStateRow
err := row.Scan(&i.Paused, &i.PausedUntil, &i.ExcludedNodes)
return i, err
}
const hasForeignReporter = `-- name: HasForeignReporter :one
SELECT (EXISTS (
SELECT 1 FROM polling_foreign_targets ft
JOIN polling_foreign_claims fc ON fc.observer_public_key = ft.observer_public_key
WHERE ft.target_public_key = $1 AND fc.received_at > $2
) OR EXISTS (
SELECT 1 FROM repeater_readings r
WHERE r.target_public_key = $1 AND r.foreign_source AND r.received_at > $3
))::boolean AS found
`
type HasForeignReporterParams struct {
TargetPublicKey []byte `json:"target_public_key"`
ClaimsAfter pgtype.Timestamptz `json:"claims_after"`
ReadingsAfter pgtype.Timestamptz `json:"readings_after"`
}
// True when an observer this server does not manage is checking the target: a live foreign claim names it, or a
// foreign reading of it arrived after readings_after.
func (q *Queries) HasForeignReporter(ctx context.Context, arg HasForeignReporterParams) (bool, error) {
row := q.db.QueryRow(ctx, hasForeignReporter, arg.TargetPublicKey, arg.ClaimsAfter, arg.ReadingsAfter)
var found bool
err := row.Scan(&found)
return found, err
}
const hasLivePollingCandidate = `-- name: HasLivePollingCandidate :one
SELECT EXISTS (
SELECT 1 FROM polling_candidates c
JOIN polling_claims cl ON cl.observer_public_key = c.observer_public_key
WHERE c.observer_public_key = $1 AND c.target_public_key = $2 AND cl.received_at > $3
)
`
type HasLivePollingCandidateParams struct {
ObserverPublicKey []byte `json:"observer_public_key"`
TargetPublicKey []byte `json:"target_public_key"`
ReceivedAt pgtype.Timestamptz `json:"received_at"`
}
func (q *Queries) HasLivePollingCandidate(ctx context.Context, arg HasLivePollingCandidateParams) (bool, error) {
row := q.db.QueryRow(ctx, hasLivePollingCandidate, arg.ObserverPublicKey, arg.TargetPublicKey, arg.ReceivedAt)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const insertForeignTarget = `-- name: InsertForeignTarget :exec
INSERT INTO polling_foreign_targets (observer_public_key, target_public_key, state, misses)
VALUES ($1, $2, $3, $4)
ON CONFLICT (observer_public_key, target_public_key) DO NOTHING
`
type InsertForeignTargetParams struct {
ObserverPublicKey []byte `json:"observer_public_key"`
TargetPublicKey []byte `json:"target_public_key"`
State string `json:"state"`
Misses int16 `json:"misses"`
}
func (q *Queries) InsertForeignTarget(ctx context.Context, arg InsertForeignTargetParams) error {
_, err := q.db.Exec(ctx, insertForeignTarget,
arg.ObserverPublicKey,
arg.TargetPublicKey,
arg.State,
arg.Misses,
)
return err
}
const insertPollingAssignment = `-- name: InsertPollingAssignment :exec
INSERT INTO polling_assignments (target_public_key, observer_public_key, rank, evidence_snr, evidence_count, assigned_at, requested)
VALUES ($1, $2, $3, $4, $5, $6, $7)
`
type InsertPollingAssignmentParams struct {
TargetPublicKey []byte `json:"target_public_key"`
ObserverPublicKey []byte `json:"observer_public_key"`
Rank int16 `json:"rank"`
EvidenceSnr *float32 `json:"evidence_snr"`
EvidenceCount int32 `json:"evidence_count"`
AssignedAt pgtype.Timestamptz `json:"assigned_at"`
Requested bool `json:"requested"`
}
func (q *Queries) InsertPollingAssignment(ctx context.Context, arg InsertPollingAssignmentParams) error {
_, err := q.db.Exec(ctx, insertPollingAssignment,
arg.TargetPublicKey,
arg.ObserverPublicKey,
arg.Rank,
arg.EvidenceSnr,
arg.EvidenceCount,
arg.AssignedAt,
arg.Requested,
)
return err
}
const insertPollingCandidate = `-- name: InsertPollingCandidate :exec
INSERT INTO polling_candidates (observer_public_key, target_public_key, key_mode, claimed_snr, requested, state, misses, last_attempt, last_ok)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (observer_public_key, target_public_key) DO NOTHING
`
type InsertPollingCandidateParams struct {
ObserverPublicKey []byte `json:"observer_public_key"`
TargetPublicKey []byte `json:"target_public_key"`
KeyMode string `json:"key_mode"`
ClaimedSnr *float32 `json:"claimed_snr"`
Requested bool `json:"requested"`
State string `json:"state"`
Misses int16 `json:"misses"`
LastAttempt pgtype.Timestamptz `json:"last_attempt"`
LastOk pgtype.Timestamptz `json:"last_ok"`
}
func (q *Queries) InsertPollingCandidate(ctx context.Context, arg InsertPollingCandidateParams) error {
_, err := q.db.Exec(ctx, insertPollingCandidate,
arg.ObserverPublicKey,
arg.TargetPublicKey,
arg.KeyMode,
arg.ClaimedSnr,
arg.Requested,
arg.State,
arg.Misses,
arg.LastAttempt,
arg.LastOk,
)
return err
}
const insertRepeaterReading = `-- name: InsertRepeaterReading :execrows
INSERT INTO repeater_readings (
target_public_key, observer_public_key, observer_id, sampled_at, received_at, method, tag,
battery_mv, temperature_c, poll_snr, poll_rssi, signed,
uptime_secs, packets_recv, packets_sent, recv_flood, recv_direct, sent_flood, sent_direct,
tx_air_secs, rx_air_secs, recv_errors, noise_floor, last_rssi, tx_queue, flood_dups, direct_dups, err_events, last_snr,
lpp, sensors, packet_hash, client, foreign_source, trusted)
SELECT
$1, $2,
$3, $4, $5, $6, $7,
$8, $9, $10, $11, $12,
$13, $14, $15, $16, $17,
$18, $19, $20, $21, $22,
$23, $24, $25, $26, $27,
$28, $29,
$30, $31::jsonb, $32, $33,
-- A reading with no claim behind it is foreign unless this server gave the observer the target: a requested
-- target is assigned before the device's claim names it.
($34::boolean AND NOT EXISTS (
SELECT 1 FROM polling_assignments t
WHERE t.target_public_key = $1 AND t.observer_public_key = $2)),
-- Same rule as latest_ts in PollingOwnerRows, frozen at insert time. A foreign observer holds no assignment, so
-- its reading is trusted on the same evidence an election would have counted: zero-hop adverts of the target it
-- heard since evidence_since, missing signal left out.
-- With polling.authority approved only an approved observer's readings count, foreign or not.
CASE WHEN $34::boolean AND NOT EXISTS (
SELECT 1 FROM polling_assignments t
WHERE t.target_public_key = $1 AND t.observer_public_key = $2
) THEN (NOT $35::boolean OR EXISTS (
SELECT 1 FROM polling_observers po
WHERE po.observer_public_key = $2 AND po.approved
)) AND EXISTS (
SELECT 1 FROM packets p
JOIN packet_observations o ON o.packet_hash = p.packet_hash
WHERE p.origin_pubkey = $1 AND p.payload_type = 4
AND o.observer_id = $3::uuid AND o.hop_count = 0 AND o.snr IS NOT NULL
AND p.first_heard_at >= $36::timestamptz AND NOT (o.snr = 0 AND o.rssi = 0)
) ELSE EXISTS (
SELECT 1 FROM polling_assignments t
WHERE t.target_public_key = $1 AND t.observer_public_key = $2
AND t.evidence_count > 0
) END
WHERE NOT EXISTS (
SELECT 1 FROM repeater_readings x
WHERE x.target_public_key = $1 AND x.observer_public_key = $2
AND x.method = $6 AND x.received_at > $37
) AND (
SELECT count(*) FROM repeater_readings b
WHERE b.observer_public_key = $2 AND b.received_at > $38
) < $39::bigint
ON CONFLICT (target_public_key, observer_public_key, tag, method) DO NOTHING
`
type InsertRepeaterReadingParams struct {
TargetPublicKey []byte `json:"target_public_key"`
ObserverPublicKey []byte `json:"observer_public_key"`
ObserverID pgtype.UUID `json:"observer_id"`
SampledAt pgtype.Timestamptz `json:"sampled_at"`
ReceivedAt pgtype.Timestamptz `json:"received_at"`
Method string `json:"method"`
Tag int64 `json:"tag"`
BatteryMv *int32 `json:"battery_mv"`
TemperatureC *float32 `json:"temperature_c"`
PollSnr *float32 `json:"poll_snr"`
PollRssi *int16 `json:"poll_rssi"`
Signed bool `json:"signed"`
UptimeSecs *int64 `json:"uptime_secs"`
PacketsRecv *int64 `json:"packets_recv"`
PacketsSent *int64 `json:"packets_sent"`
RecvFlood *int64 `json:"recv_flood"`
RecvDirect *int64 `json:"recv_direct"`
SentFlood *int64 `json:"sent_flood"`
SentDirect *int64 `json:"sent_direct"`
TxAirSecs *int64 `json:"tx_air_secs"`
RxAirSecs *int64 `json:"rx_air_secs"`
RecvErrors *int64 `json:"recv_errors"`
NoiseFloor *int32 `json:"noise_floor"`
LastRssi *int32 `json:"last_rssi"`
TxQueue *int32 `json:"tx_queue"`
FloodDups *int32 `json:"flood_dups"`
DirectDups *int32 `json:"direct_dups"`
ErrEvents *int32 `json:"err_events"`
LastSnr *float32 `json:"last_snr"`
Lpp []byte `json:"lpp"`
Sensors []byte `json:"sensors"`
PacketHash []byte `json:"packet_hash"`
Client string `json:"client"`
ForeignSource bool `json:"foreign_source"`
ApprovedOnly bool `json:"approved_only"`
EvidenceSince pgtype.Timestamptz `json:"evidence_since"`
RecentAfter pgtype.Timestamptz `json:"recent_after"`
BudgetAfter pgtype.Timestamptz `json:"budget_after"`
Budget int64 `json:"budget"`
}
// Run under LockPollingObserver. Inserts nothing when this observer stored a reading of the target by the same
// method received after recent_after, or budget readings of any target received after budget_after.
func (q *Queries) InsertRepeaterReading(ctx context.Context, arg InsertRepeaterReadingParams) (int64, error) {
result, err := q.db.Exec(ctx, insertRepeaterReading,
arg.TargetPublicKey,
arg.ObserverPublicKey,
arg.ObserverID,
arg.SampledAt,
arg.ReceivedAt,
arg.Method,
arg.Tag,
arg.BatteryMv,
arg.TemperatureC,
arg.PollSnr,
arg.PollRssi,
arg.Signed,
arg.UptimeSecs,
arg.PacketsRecv,
arg.PacketsSent,
arg.RecvFlood,
arg.RecvDirect,
arg.SentFlood,
arg.SentDirect,
arg.TxAirSecs,
arg.RxAirSecs,
arg.RecvErrors,
arg.NoiseFloor,
arg.LastRssi,
arg.TxQueue,
arg.FloodDups,
arg.DirectDups,
arg.ErrEvents,
arg.LastSnr,
arg.Lpp,
arg.Sensors,
arg.PacketHash,
arg.Client,
arg.ForeignSource,
arg.ApprovedOnly,
arg.EvidenceSince,
arg.RecentAfter,
arg.BudgetAfter,
arg.Budget,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
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)
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. 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
err := row.Scan(&column_1)
return column_1, err
}
const latestNodeReadings = `-- name: LatestNodeReadings :many
WITH targets AS (
SELECT target_public_key FROM polling_assignments
UNION
SELECT DISTINCT target_public_key FROM repeater_readings WHERE trusted AND sampled_at >= $1::timestamptz AND received_at >= $1::timestamptz
)
SELECT n.id AS node_id, b.battery_mv, t.temperature_c,
GREATEST(b.sampled_at, t.sampled_at)::timestamptz AS sampled_at
FROM targets tg
JOIN nodes n ON n.public_key = tg.target_public_key
LEFT JOIN LATERAL (
SELECT r.battery_mv, r.sampled_at FROM repeater_readings r
WHERE r.target_public_key = n.public_key AND r.trusted AND r.battery_mv IS NOT NULL AND r.sampled_at >= $1::timestamptz
ORDER BY r.sampled_at DESC, r.id DESC LIMIT 1
) b ON true
LEFT JOIN LATERAL (
SELECT r.temperature_c, r.sampled_at FROM repeater_readings r
WHERE r.target_public_key = n.public_key AND r.trusted AND r.temperature_c IS NOT NULL AND r.sampled_at >= $1::timestamptz
ORDER BY r.sampled_at DESC, r.id DESC LIMIT 1
) t ON true
WHERE (b.sampled_at IS NOT NULL OR t.sampled_at IS NOT NULL)
AND (COALESCE(cardinality($2::bpchar[]), 0) = 0 OR n.id IN (SELECT node_id FROM node_iatas WHERE iata = ANY($2::bpchar[])))
ORDER BY n.id
`
type LatestNodeReadingsParams struct {
Since pgtype.Timestamptz `json:"since"`
Iatas []string `json:"iatas"`
}
type LatestNodeReadingsRow struct {
NodeID uuid.UUID `json:"node_id"`
BatteryMv *int32 `json:"battery_mv"`
TemperatureC *float32 `json:"temperature_c"`
SampledAt pgtype.Timestamptz `json:"sampled_at"`
}
// 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.
func (q *Queries) LatestNodeReadings(ctx context.Context, arg LatestNodeReadingsParams) ([]LatestNodeReadingsRow, error) {
rows, err := q.db.Query(ctx, latestNodeReadings, arg.Since, arg.Iatas)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LatestNodeReadingsRow{}
for rows.Next() {
var i LatestNodeReadingsRow
if err := rows.Scan(
&i.NodeID,
&i.BatteryMv,
&i.TemperatureC,
&i.SampledAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const latestNodeStatusReadingBefore = `-- name: LatestNodeStatusReadingBefore :many
SELECT sampled_at, method, trusted, foreign_source, battery_mv, temperature_c, noise_floor, last_rssi, last_snr, uptime_secs, tx_queue,
tx_air_secs, rx_air_secs, packets_recv, packets_sent, recv_errors, sensors
FROM repeater_readings
WHERE target_public_key = $1
AND sampled_at < $2::timestamptz
AND method = 'status'
AND (trusted OR $3::boolean)
ORDER BY sampled_at DESC, id DESC
LIMIT 1
`
type LatestNodeStatusReadingBeforeParams struct {
TargetPublicKey []byte `json:"target_public_key"`
Since pgtype.Timestamptz `json:"since"`
IncludeUntrusted bool `json:"include_untrusted"`
}
type LatestNodeStatusReadingBeforeRow struct {
SampledAt pgtype.Timestamptz `json:"sampled_at"`
Method string `json:"method"`
Trusted bool `json:"trusted"`
ForeignSource bool `json:"foreign_source"`
BatteryMv *int32 `json:"battery_mv"`
TemperatureC *float32 `json:"temperature_c"`
NoiseFloor *int32 `json:"noise_floor"`
LastRssi *int32 `json:"last_rssi"`
LastSnr *float32 `json:"last_snr"`
UptimeSecs *int64 `json:"uptime_secs"`
TxQueue *int32 `json:"tx_queue"`
TxAirSecs *int64 `json:"tx_air_secs"`
RxAirSecs *int64 `json:"rx_air_secs"`
PacketsRecv *int64 `json:"packets_recv"`
PacketsSent *int64 `json:"packets_sent"`
RecvErrors *int64 `json:"recv_errors"`
Sensors []byte `json:"sensors"`
}
// The newest status reading before since: the baseline for the first counter increments in range.
func (q *Queries) LatestNodeStatusReadingBefore(ctx context.Context, arg LatestNodeStatusReadingBeforeParams) ([]LatestNodeStatusReadingBeforeRow, error) {
rows, err := q.db.Query(ctx, latestNodeStatusReadingBefore, arg.TargetPublicKey, arg.Since, arg.IncludeUntrusted)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LatestNodeStatusReadingBeforeRow{}
for rows.Next() {
var i LatestNodeStatusReadingBeforeRow
if err := rows.Scan(
&i.SampledAt,
&i.Method,
&i.Trusted,
&i.ForeignSource,
&i.BatteryMv,
&i.TemperatureC,
&i.NoiseFloor,
&i.LastRssi,
&i.LastSnr,
&i.UptimeSecs,
&i.TxQueue,
&i.TxAirSecs,
&i.RxAirSecs,
&i.PacketsRecv,
&i.PacketsSent,
&i.RecvErrors,
&i.Sensors,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listForeignReporters = `-- name: ListForeignReporters :many
WITH keys AS (
SELECT ft.observer_public_key FROM polling_foreign_targets ft
JOIN polling_foreign_claims fc ON fc.observer_public_key = ft.observer_public_key
WHERE ft.target_public_key = $1 AND fc.received_at > $2
UNION
SELECT r.observer_public_key FROM repeater_readings r
WHERE r.target_public_key = $1 AND r.foreign_source AND r.received_at > $3
)
SELECT o.id AS observer_id,
COALESCE(NULLIF(o.display_name, ''), left(encode(o.public_key, 'hex'), 8))::text AS name,
COALESCE(fc.poll_host, '')::text AS poll_host, COALESCE(fc.signed, false)::boolean AS signed,
-- claimed is about this target: the observer's live claim can name others only.
(fc.observer_public_key IS NOT NULL AND EXISTS (
SELECT 1 FROM polling_foreign_targets ft
WHERE ft.observer_public_key = k.observer_public_key AND ft.target_public_key = $1))::boolean AS claimed,
-- local is about the observer: no stored claim of either kind, live or not.
(NOT EXISTS (SELECT 1 FROM polling_foreign_claims a WHERE a.observer_public_key = k.observer_public_key)
AND NOT EXISTS (SELECT 1 FROM polling_claims c WHERE c.observer_public_key = k.observer_public_key))::boolean AS is_local,
(SELECT r.sampled_at FROM repeater_readings r
WHERE r.target_public_key = $1 AND r.observer_public_key = k.observer_public_key
ORDER BY r.sampled_at DESC LIMIT 1)::timestamptz AS latest_reading_at
FROM keys k
JOIN observers o ON o.public_key = k.observer_public_key
LEFT JOIN polling_foreign_claims fc ON fc.observer_public_key = k.observer_public_key AND fc.received_at > $2
ORDER BY name, o.id
`
type ListForeignReportersParams struct {
TargetPublicKey []byte `json:"target_public_key"`
ClaimsAfter pgtype.Timestamptz `json:"claims_after"`
ReadingsAfter pgtype.Timestamptz `json:"readings_after"`
}
type ListForeignReportersRow struct {
ObserverID uuid.UUID `json:"observer_id"`
Name string `json:"name"`
PollHost string `json:"poll_host"`
Signed bool `json:"signed"`
Claimed bool `json:"claimed"`
IsLocal bool `json:"is_local"`
LatestReadingAt pgtype.Timestamptz `json:"latest_reading_at"`
}
// The observers HasForeignReporter counts, each with its claim (NULL for one that only sends readings) and the
// newest reading it delivered for the target. An observer without a row is left out.
func (q *Queries) ListForeignReporters(ctx context.Context, arg ListForeignReportersParams) ([]ListForeignReportersRow, error) {
rows, err := q.db.Query(ctx, listForeignReporters, arg.TargetPublicKey, arg.ClaimsAfter, arg.ReadingsAfter)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListForeignReportersRow{}
for rows.Next() {
var i ListForeignReportersRow
if err := rows.Scan(
&i.ObserverID,
&i.Name,
&i.PollHost,
&i.Signed,
&i.Claimed,
&i.IsLocal,
&i.LatestReadingAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listNodeReadings = `-- name: ListNodeReadings :many
SELECT sampled_at, method, trusted, foreign_source, battery_mv, temperature_c, noise_floor, last_rssi, last_snr, uptime_secs, tx_queue,
tx_air_secs, rx_air_secs, packets_recv, packets_sent, recv_errors, sensors
FROM repeater_readings
WHERE target_public_key = $1
AND sampled_at >= $2::timestamptz
AND ($3::timestamptz IS NULL OR sampled_at < $3::timestamptz)
AND (trusted OR $4::boolean)
ORDER BY sampled_at ASC, id ASC
`
type ListNodeReadingsParams struct {
TargetPublicKey []byte `json:"target_public_key"`
Since pgtype.Timestamptz `json:"since"`
Until pgtype.Timestamptz `json:"until"`
IncludeUntrusted bool `json:"include_untrusted"`
}
type ListNodeReadingsRow struct {
SampledAt pgtype.Timestamptz `json:"sampled_at"`
Method string `json:"method"`
Trusted bool `json:"trusted"`
ForeignSource bool `json:"foreign_source"`
BatteryMv *int32 `json:"battery_mv"`
TemperatureC *float32 `json:"temperature_c"`
NoiseFloor *int32 `json:"noise_floor"`
LastRssi *int32 `json:"last_rssi"`
LastSnr *float32 `json:"last_snr"`
UptimeSecs *int64 `json:"uptime_secs"`
TxQueue *int32 `json:"tx_queue"`
TxAirSecs *int64 `json:"tx_air_secs"`
RxAirSecs *int64 `json:"rx_air_secs"`
PacketsRecv *int64 `json:"packets_recv"`
PacketsSent *int64 `json:"packets_sent"`
RecvErrors *int64 `json:"recv_errors"`
Sensors []byte `json:"sensors"`
}
// Readings of one target in [since, until) ascending; until is open when NULL. Untrusted ones only when asked for.
func (q *Queries) ListNodeReadings(ctx context.Context, arg ListNodeReadingsParams) ([]ListNodeReadingsRow, error) {
rows, err := q.db.Query(ctx, listNodeReadings,
arg.TargetPublicKey,
arg.Since,
arg.Until,
arg.IncludeUntrusted,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListNodeReadingsRow{}
for rows.Next() {
var i ListNodeReadingsRow
if err := rows.Scan(
&i.SampledAt,
&i.Method,
&i.Trusted,
&i.ForeignSource,
&i.BatteryMv,
&i.TemperatureC,
&i.NoiseFloor,
&i.LastRssi,
&i.LastSnr,
&i.UptimeSecs,
&i.TxQueue,
&i.TxAirSecs,
&i.RxAirSecs,
&i.PacketsRecv,
&i.PacketsSent,
&i.RecvErrors,
&i.Sensors,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listObserverPollingTargets = `-- name: ListObserverPollingTargets :many
SELECT c.target_public_key FROM polling_candidates c WHERE c.observer_public_key = $1
UNION
SELECT a.target_public_key FROM polling_assignments a WHERE a.observer_public_key = $1
ORDER BY 1
`
// Every target the observer's own claim names or it holds an assignment for: what leaving the elections touches.
func (q *Queries) ListObserverPollingTargets(ctx context.Context, observerPublicKey []byte) ([][]byte, error) {
rows, err := q.db.Query(ctx, listObserverPollingTargets, observerPublicKey)
if err != nil {
return nil, err
}
defer rows.Close()
items := [][]byte{}
for rows.Next() {
var target_public_key []byte
if err := rows.Scan(&target_public_key); err != nil {
return nil, err
}
items = append(items, target_public_key)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listObserverRequestedSeats = `-- name: ListObserverRequestedSeats :many
SELECT x.target_public_key::bytea AS target_public_key, q.oldest::timestamptz AS oldest
FROM polling_assignments x
JOIN polling_targets pt ON pt.target_public_key = x.target_public_key AND pt.active_request_id IS NOT NULL
JOIN LATERAL (SELECT min(r.created_at) AS oldest FROM telemetry_requests r WHERE r.target_public_key = x.target_public_key) q ON true
WHERE x.observer_public_key = $1 AND x.requested
AND x.target_public_key <> $2 AND q.oldest IS NOT NULL
ORDER BY q.oldest, x.target_public_key
`
type ListObserverRequestedSeatsParams struct {
ObserverPublicKey []byte `json:"observer_public_key"`
TargetPublicKey []byte `json:"target_public_key"`
}
type ListObserverRequestedSeatsRow struct {
TargetPublicKey []byte `json:"target_public_key"`
Oldest pgtype.Timestamptz `json:"oldest"`
}
// The observer's requested assignments to other targets that are still requested, with the age of each target's
// oldest request, oldest first. A withdrawn target's assignment waits for its own election and holds no seat.
func (q *Queries) ListObserverRequestedSeats(ctx context.Context, arg ListObserverRequestedSeatsParams) ([]ListObserverRequestedSeatsRow, error) {
rows, err := q.db.Query(ctx, listObserverRequestedSeats, arg.ObserverPublicKey, arg.TargetPublicKey)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListObserverRequestedSeatsRow{}
for rows.Next() {
var i ListObserverRequestedSeatsRow
if err := rows.Scan(&i.TargetPublicKey, &i.Oldest); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listOrphanPollingTargets = `-- name: ListOrphanPollingTargets :many
SELECT DISTINCT a.target_public_key FROM polling_assignments a
WHERE NOT EXISTS (
SELECT 1 FROM polling_candidates c
WHERE c.target_public_key = a.target_public_key AND c.observer_public_key = a.observer_public_key
) AND NOT (a.requested AND EXISTS (
SELECT 1 FROM polling_claims cl WHERE cl.observer_public_key = a.observer_public_key AND cl.accepts_requests
))
ORDER BY a.target_public_key
`
// Targets with an assignment whose candidate is gone. A requested assignment is kept while its observer's claim
// accepts requests: it is made before the device lists the target, and the claim rows of an expired claim are gone.
func (q *Queries) ListOrphanPollingTargets(ctx context.Context) ([][]byte, error) {
rows, err := q.db.Query(ctx, listOrphanPollingTargets)
if err != nil {
return nil, err
}
defer rows.Close()
items := [][]byte{}
for rows.Next() {
var target_public_key []byte
if err := rows.Scan(&target_public_key); err != nil {
return nil, err
}
items = append(items, target_public_key)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listPollingCandidates = `-- name: ListPollingCandidates :many
SELECT c.observer_public_key, c.claimed_snr, c.state, c.misses, c.requested,
COALESCE(po.blocked, false) AS blocked, COALESCE(po.approved, false) AS approved,
ev.n AS evidence_count, ev.mean_snr AS evidence_snr
FROM polling_candidates c
JOIN polling_claims cl ON cl.observer_public_key = c.observer_public_key
LEFT JOIN polling_observers po ON po.observer_public_key = c.observer_public_key
LEFT JOIN LATERAL (
SELECT count(o.snr) AS n, COALESCE(avg(o.snr), 0)::float8 AS mean_snr
FROM packets p
JOIN packet_observations o ON o.packet_hash = p.packet_hash
WHERE p.origin_pubkey = c.target_public_key AND p.payload_type = 4
AND o.observer_id = cl.observer_id AND o.hop_count = 0
AND p.first_heard_at >= $3 AND NOT (o.snr = 0 AND o.rssi = 0)
) ev ON true
WHERE c.target_public_key = $1 AND cl.received_at > $2
ORDER BY c.observer_public_key
`
type ListPollingCandidatesParams struct {
TargetPublicKey []byte `json:"target_public_key"`
ReceivedAt pgtype.Timestamptz `json:"received_at"`
FirstHeardAt pgtype.Timestamptz `json:"first_heard_at"`
}
type ListPollingCandidatesRow struct {
ObserverPublicKey []byte `json:"observer_public_key"`
ClaimedSnr *float32 `json:"claimed_snr"`
State string `json:"state"`
Misses int16 `json:"misses"`
Requested bool `json:"requested"`
Blocked bool `json:"blocked"`
Approved bool `json:"approved"`
EvidenceCount int64 `json:"evidence_count"`
EvidenceSnr float64 `json:"evidence_snr"`
}
// Evidence: zero-hop adverts of the target this observer heard since $3, with missing signal (0/0) left out. mean_snr is 0 when n is 0.
func (q *Queries) ListPollingCandidates(ctx context.Context, arg ListPollingCandidatesParams) ([]ListPollingCandidatesRow, error) {
rows, err := q.db.Query(ctx, listPollingCandidates, arg.TargetPublicKey, arg.ReceivedAt, arg.FirstHeardAt)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListPollingCandidatesRow{}
for rows.Next() {
var i ListPollingCandidatesRow
if err := rows.Scan(
&i.ObserverPublicKey,
&i.ClaimedSnr,
&i.State,
&i.Misses,
&i.Requested,
&i.Blocked,
&i.Approved,
&i.EvidenceCount,
&i.EvidenceSnr,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listPollingObservers = `-- name: ListPollingObservers :many
SELECT observer_public_key, blocked, approved, note FROM polling_observers ORDER BY observer_public_key
`
func (q *Queries) ListPollingObservers(ctx context.Context) ([]PollingObserver, error) {
rows, err := q.db.Query(ctx, listPollingObservers)
if err != nil {
return nil, err
}
defer rows.Close()
items := []PollingObserver{}
for rows.Next() {
var i PollingObserver
if err := rows.Scan(
&i.ObserverPublicKey,
&i.Blocked,
&i.Approved,
&i.Note,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listPollingTargets = `-- name: ListPollingTargets :many
SELECT target_public_key::bytea AS target_public_key FROM (
SELECT c.target_public_key FROM polling_candidates c
JOIN polling_claims cl ON cl.observer_public_key = c.observer_public_key
WHERE cl.received_at > $1
AND NOT EXISTS (SELECT 1 FROM observers o
WHERE o.public_key = c.target_public_key AND o.last_status_at >= $2)
UNION
SELECT a.target_public_key FROM polling_assignments a
UNION
SELECT pt.target_public_key FROM polling_targets pt WHERE pt.active_request_id IS NOT NULL
) t
ORDER BY target_public_key
`
type ListPollingTargetsParams struct {
ReceivedAfter pgtype.Timestamptz `json:"received_after"`
StatusAfter pgtype.Timestamptz `json:"status_after"`
}
// A target with only expired claims is still listed while it has assignment rows, so the caller can clear them. A
// requested target is always listed, so its requests move between waiting and active. An observer that sent status
// since status_after is never polled, so a claim alone does not list one; leftover assignments still do, to clear them.
func (q *Queries) ListPollingTargets(ctx context.Context, arg ListPollingTargetsParams) ([][]byte, error) {
rows, err := q.db.Query(ctx, listPollingTargets, arg.ReceivedAfter, arg.StatusAfter)
if err != nil {
return nil, err
}
defer rows.Close()
items := [][]byte{}
for rows.Next() {
var target_public_key []byte
if err := rows.Scan(&target_public_key); err != nil {
return nil, err
}
items = append(items, target_public_key)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listRequestCandidates = `-- name: ListRequestCandidates :many
WITH me AS (
SELECT min(created_at) AS oldest FROM telemetry_requests WHERE target_public_key = $1
), ev AS (
SELECT o.observer_id, count(o.snr) AS n, COALESCE(avg(o.snr), 0)::float8 AS mean_snr
FROM packets p
JOIN packet_observations o ON o.packet_hash = p.packet_hash
WHERE p.origin_pubkey = $1 AND p.payload_type = 4
AND o.hop_count = 0 AND p.first_heard_at >= $3 AND NOT (o.snr = 0 AND o.rssi = 0)
GROUP BY o.observer_id
)
SELECT cl.observer_public_key, c.claimed_snr, COALESCE(c.state, '')::text AS state, COALESCE(c.misses, 0)::smallint AS misses,
COALESCE(c.requested, false)::boolean AS requested,
COALESCE(po.blocked, false) AS blocked, COALESCE(po.approved, false) AS approved,
cl.request_slots::int AS request_slots, COALESCE(cl.max_slots, 0)::int AS max_slots,
(SELECT count(*) FROM polling_candidates h WHERE h.observer_public_key = cl.observer_public_key AND h.requested)::int AS held,
EXISTS (SELECT 1 FROM polling_admin_stops s
WHERE s.target_public_key = $1 AND s.observer_public_key = cl.observer_public_key) AS admin_stopped,
(SELECT count(*) FROM polling_assignments x
JOIN polling_targets pt ON pt.target_public_key = x.target_public_key AND pt.active_request_id IS NOT NULL
JOIN LATERAL (SELECT min(r.created_at) AS oldest FROM telemetry_requests r WHERE r.target_public_key = x.target_public_key) q ON true
WHERE x.observer_public_key = cl.observer_public_key AND x.requested
AND x.target_public_key <> $1 AND q.oldest IS NOT NULL
AND (q.oldest, x.target_public_key) < (me.oldest, $1::bytea))::int AS seats_elsewhere,
ev.n AS evidence_count, ev.mean_snr AS evidence_snr
FROM polling_claims cl
CROSS JOIN me
JOIN ev ON ev.observer_id = cl.observer_id AND ev.n > 0
LEFT JOIN polling_candidates c ON c.observer_public_key = cl.observer_public_key AND c.target_public_key = $1
LEFT JOIN polling_observers po ON po.observer_public_key = cl.observer_public_key
WHERE cl.accepts_requests AND cl.received_at > $2
ORDER BY cl.observer_public_key
`
type ListRequestCandidatesParams struct {
TargetPublicKey []byte `json:"target_public_key"`
ReceivedAfter pgtype.Timestamptz `json:"received_after"`
FirstHeardAt pgtype.Timestamptz `json:"first_heard_at"`
}
type ListRequestCandidatesRow struct {
ObserverPublicKey []byte `json:"observer_public_key"`
ClaimedSnr *float32 `json:"claimed_snr"`
State string `json:"state"`
Misses int16 `json:"misses"`
Requested bool `json:"requested"`
Blocked bool `json:"blocked"`
Approved bool `json:"approved"`
RequestSlots int32 `json:"request_slots"`
MaxSlots int32 `json:"max_slots"`
Held int32 `json:"held"`
AdminStopped bool `json:"admin_stopped"`
SeatsElsewhere int32 `json:"seats_elsewhere"`
EvidenceCount int64 `json:"evidence_count"`
EvidenceSnr float64 `json:"evidence_snr"`
}
// Observers that could take a requested target: a live claim that accepts requests and zero-hop advert evidence for
// the target since first_heard_at (missing signal 0/0 left out). They need not name the target in their claim: a
// device learns of a requested target from the owners answer. held counts the requested targets the claim names;
// seats_elsewhere counts this observer's requested assignments to other still-requested targets whose oldest request
// is older than this target's, so seats go to the oldest requests first.
func (q *Queries) ListRequestCandidates(ctx context.Context, arg ListRequestCandidatesParams) ([]ListRequestCandidatesRow, error) {
rows, err := q.db.Query(ctx, listRequestCandidates, arg.TargetPublicKey, arg.ReceivedAfter, arg.FirstHeardAt)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListRequestCandidatesRow{}
for rows.Next() {
var i ListRequestCandidatesRow
if err := rows.Scan(
&i.ObserverPublicKey,
&i.ClaimedSnr,
&i.State,
&i.Misses,
&i.Requested,
&i.Blocked,
&i.Approved,
&i.RequestSlots,
&i.MaxSlots,
&i.Held,
&i.AdminStopped,
&i.SeatsElsewhere,
&i.EvidenceCount,
&i.EvidenceSnr,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listRequestObserverKeys = `-- name: ListRequestObserverKeys :many
SELECT observer_public_key FROM polling_claims WHERE accepts_requests AND received_at > $1 ORDER BY observer_public_key
`
// The observers whose claim accepts requests, in key order, which is the order their seat locks are taken in.
func (q *Queries) ListRequestObserverKeys(ctx context.Context, receivedAt pgtype.Timestamptz) ([][]byte, error) {
rows, err := q.db.Query(ctx, listRequestObserverKeys, receivedAt)
if err != nil {
return nil, err
}
defer rows.Close()
items := [][]byte{}
for rows.Next() {
var observer_public_key []byte
if err := rows.Scan(&observer_public_key); err != nil {
return nil, err
}
items = append(items, observer_public_key)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listRequestedAssignedTargets = `-- name: ListRequestedAssignedTargets :many
SELECT DISTINCT target_public_key::bytea AS target_public_key FROM polling_assignments
WHERE requested AND observer_public_key = ANY($1::bytea[])
ORDER BY 1
`
// The targets that hold a requested assignment of any of the observers: the ones a seat decision may take a seat
// from, locked with the election in key order.
func (q *Queries) ListRequestedAssignedTargets(ctx context.Context, observers [][]byte) ([][]byte, error) {
rows, err := q.db.Query(ctx, listRequestedAssignedTargets, observers)
if err != nil {
return nil, err
}
defer rows.Close()
items := [][]byte{}
for rows.Next() {
var target_public_key []byte
if err := rows.Scan(&target_public_key); err != nil {
return nil, err
}
items = append(items, target_public_key)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockPollingObserver = `-- name: LockPollingObserver :exec
SELECT pg_advisory_xact_lock(25191, hashtext(current_schema() || encode($1::bytea, 'hex')))
`
// Serializes one observer's reading inserts until the transaction ends, so its rate and budget checks see each
// other. Class 25191, beside the target class and the (25189, n) job locks.
func (q *Queries) LockPollingObserver(ctx context.Context, observerPublicKey []byte) error {
_, err := q.db.Exec(ctx, lockPollingObserver, observerPublicKey)
return err
}
const lockPollingSeats = `-- name: LockPollingSeats :exec
SELECT pg_advisory_xact_lock(25192, hashtext(current_schema() || encode($1::bytea, 'hex')))
`
// Serializes the seat decisions of one observer until the transaction ends. Class 25192, beside the target class
// (25190) and the reading-insert class (25191). Taken before the target lock, in key order, so two elections
// cannot wait on each other.
func (q *Queries) LockPollingSeats(ctx context.Context, observerPublicKey []byte) error {
_, err := q.db.Exec(ctx, lockPollingSeats, observerPublicKey)
return err
}
const lockPollingTarget = `-- name: LockPollingTarget :exec
SELECT pg_advisory_xact_lock(25190, hashtext(current_schema() || encode($1::bytea, 'hex')))
`
// Serializes elections of one target until the transaction ends. Class 25190 in the two-key space, which never
// meets the one-key migration lock; the schema keeps instances in other schemas apart.
func (q *Queries) LockPollingTarget(ctx context.Context, targetPublicKey []byte) error {
_, err := q.db.Exec(ctx, lockPollingTarget, targetPublicKey)
return err
}
const nodeForeignPoller = `-- name: NodeForeignPoller :many
SELECT fc.received_at, fc.poll_host, fc.signed, ft.target_public_key, ft.state, ft.misses,
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 polling_foreign_claims fc
LEFT JOIN polling_foreign_targets ft ON ft.observer_public_key = fc.observer_public_key
LEFT JOIN nodes n ON n.public_key = ft.target_public_key
LEFT JOIN LATERAL (
SELECT r.sampled_at, r.poll_rssi, r.signed FROM repeater_readings r
WHERE r.target_public_key = ft.target_public_key AND r.observer_public_key = fc.observer_public_key
ORDER BY r.sampled_at DESC LIMIT 1
) lr ON true
WHERE fc.observer_public_key = $1
ORDER BY lower(NULLIF(n.name, '')) NULLS LAST, ft.target_public_key
`
type NodeForeignPollerRow struct {
ReceivedAt pgtype.Timestamptz `json:"received_at"`
PollHost string `json:"poll_host"`
Signed bool `json:"signed"`
TargetPublicKey []byte `json:"target_public_key"`
State *string `json:"state"`
Misses *int16 `json:"misses"`
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 observer's foreign claim, live or expired, and the targets it names; one row with a NULL target when it names
// none, no rows when it has no foreign claim.
func (q *Queries) NodeForeignPoller(ctx context.Context, observerPublicKey []byte) ([]NodeForeignPollerRow, error) {
rows, err := q.db.Query(ctx, nodeForeignPoller, observerPublicKey)
if err != nil {
return nil, err
}
defer rows.Close()
items := []NodeForeignPollerRow{}
for rows.Next() {
var i NodeForeignPollerRow
if err := rows.Scan(
&i.ReceivedAt,
&i.PollHost,
&i.Signed,
&i.TargetPublicKey,
&i.State,
&i.Misses,
&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 nodeHasReadings = `-- name: NodeHasReadings :one
SELECT EXISTS (SELECT 1 FROM repeater_readings WHERE target_public_key = $1)
`
func (q *Queries) NodeHasReadings(ctx context.Context, targetPublicKey []byte) (bool, error) {
row := q.db.QueryRow(ctx, nodeHasReadings, targetPublicKey)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const nodeLatestTrustedReadingAt = `-- name: NodeLatestTrustedReadingAt :one
SELECT max(sampled_at)::timestamptz AS sampled_at FROM repeater_readings WHERE target_public_key = $1 AND trusted
`
func (q *Queries) NodeLatestTrustedReadingAt(ctx context.Context, targetPublicKey []byte) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, nodeLatestTrustedReadingAt, targetPublicKey)
var sampled_at pgtype.Timestamptz
err := row.Scan(&sampled_at)
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,
p.max_slots, p.poll_interval, p.poll_host, p.signed,
rc.readings, rc.foreign_readings,
(SELECT count(*) FROM polling_assignments x
JOIN polling_targets pt ON pt.target_public_key = x.target_public_key AND pt.active_request_id IS NOT NULL
WHERE x.observer_public_key = p.observer_public_key AND x.requested
AND NOT EXISTS (SELECT 1 FROM polling_candidates h
WHERE h.observer_public_key = x.observer_public_key AND h.target_public_key = x.target_public_key))::int AS pending_seats
FROM polling_claims p
-- One pass over the observer's recent readings for both counts.
CROSS JOIN LATERAL (
SELECT count(*)::int AS readings, (count(*) FILTER (WHERE r.foreign_source))::int AS foreign_readings
FROM repeater_readings r
WHERE r.observer_public_key = p.observer_public_key AND r.received_at > $1
) rc
WHERE p.observer_public_key = $2
)
SELECT cl.received_at, cl.accepts_requests, cl.request_slots, cl.max_slots, cl.poll_interval, cl.poll_host, cl.signed,
cl.readings, cl.foreign_readings, cl.pending_seats,
c.target_public_key, c.requested, c.state, c.misses, c.last_attempt, c.last_ok, c.claimed_snr,
a.rank, a.evidence_snr, COALESCE(a.evidence_count, 0)::int AS evidence_count,
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 cl
LEFT JOIN polling_candidates c ON c.observer_public_key = cl.observer_public_key
LEFT JOIN polling_assignments a ON a.target_public_key = c.target_public_key AND a.observer_public_key = c.observer_public_key
LEFT JOIN nodes n ON n.public_key = c.target_public_key
LEFT JOIN LATERAL (
SELECT r.sampled_at, r.poll_rssi, r.signed FROM repeater_readings r
WHERE r.target_public_key = c.target_public_key AND r.observer_public_key = c.observer_public_key
ORDER BY r.sampled_at DESC LIMIT 1
) lr ON true
ORDER BY a.rank NULLS LAST, lower(NULLIF(n.name, '')) NULLS LAST, c.target_public_key
`
type NodePollerParams struct {
ReadingsAfter pgtype.Timestamptz `json:"readings_after"`
ObserverPublicKey []byte `json:"observer_public_key"`
}
type NodePollerRow struct {
ReceivedAt pgtype.Timestamptz `json:"received_at"`
AcceptsRequests bool `json:"accepts_requests"`
RequestSlots int32 `json:"request_slots"`
MaxSlots *int16 `json:"max_slots"`
PollInterval *int32 `json:"poll_interval"`
PollHost string `json:"poll_host"`
Signed bool `json:"signed"`
Readings int32 `json:"readings"`
ForeignReadings int32 `json:"foreign_readings"`
PendingSeats int32 `json:"pending_seats"`
TargetPublicKey []byte `json:"target_public_key"`
Requested *bool `json:"requested"`
State *string `json:"state"`
Misses *int16 `json:"misses"`
LastAttempt pgtype.Timestamptz `json:"last_attempt"`
LastOk pgtype.Timestamptz `json:"last_ok"`
ClaimedSnr *float32 `json:"claimed_snr"`
Rank *int16 `json:"rank"`
EvidenceSnr *float32 `json:"evidence_snr"`
EvidenceCount int32 `json:"evidence_count"`
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 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
// been handed, for a request still in use, that its claim does not name yet.
// Targets come assigned ones first by rank. rank is NULL when the observer holds no assignment for the target.
// Evidence is the assignment's, frozen at the election. latest_reading_at is the newest reading this observer
// delivered for the target, trusted or not, with its reply rssi and whether it was signed. name is ” when the target has no node row or name.
func (q *Queries) NodePoller(ctx context.Context, arg NodePollerParams) ([]NodePollerRow, error) {
rows, err := q.db.Query(ctx, nodePoller, arg.ReadingsAfter, arg.ObserverPublicKey)
if err != nil {
return nil, err
}
defer rows.Close()
items := []NodePollerRow{}
for rows.Next() {
var i NodePollerRow
if err := rows.Scan(
&i.ReceivedAt,
&i.AcceptsRequests,
&i.RequestSlots,
&i.MaxSlots,
&i.PollInterval,
&i.PollHost,
&i.Signed,
&i.Readings,
&i.ForeignReadings,
&i.PendingSeats,
&i.TargetPublicKey,
&i.Requested,
&i.State,
&i.Misses,
&i.LastAttempt,
&i.LastOk,
&i.ClaimedSnr,
&i.Rank,
&i.EvidenceSnr,
&i.EvidenceCount,
&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 nodePollingAssignments = `-- name: NodePollingAssignments :many
SELECT o.id AS observer_id, a.rank::int AS rank,
COALESCE(NULLIF(o.display_name, ''), left(encode(o.public_key, 'hex'), 8))::text AS name
FROM polling_assignments a
JOIN observers o ON o.public_key = a.observer_public_key
WHERE a.target_public_key = $1
ORDER BY a.rank, o.id
`
type NodePollingAssignmentsRow struct {
ObserverID uuid.UUID `json:"observer_id"`
Rank int32 `json:"rank"`
Name string `json:"name"`
}
// Assigned observers of one target by rank. An assignment whose observer has no row is left out.
func (q *Queries) NodePollingAssignments(ctx context.Context, targetPublicKey []byte) ([]NodePollingAssignmentsRow, error) {
rows, err := q.db.Query(ctx, nodePollingAssignments, targetPublicKey)
if err != nil {
return nil, err
}
defer rows.Close()
items := []NodePollingAssignmentsRow{}
for rows.Next() {
var i NodePollingAssignmentsRow
if err := rows.Scan(&i.ObserverID, &i.Rank, &i.Name); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const nodePublicKey = `-- name: NodePublicKey :one
SELECT public_key FROM nodes WHERE id = $1
`
func (q *Queries) NodePublicKey(ctx context.Context, id uuid.UUID) ([]byte, error) {
row := q.db.QueryRow(ctx, nodePublicKey, id)
var public_key []byte
err := row.Scan(&public_key)
return public_key, err
}
const observerClaimRows = `-- name: ObserverClaimRows :many
SELECT false AS is_foreign, pc.claimed_at, pc.received_at, pc.signed
FROM polling_claims pc WHERE pc.observer_public_key = $1
UNION ALL
SELECT true, fc.claimed_at, fc.received_at, fc.signed
FROM polling_foreign_claims fc WHERE fc.observer_public_key = $1
`
type ObserverClaimRowsRow struct {
IsForeign bool `json:"is_foreign"`
ClaimedAt pgtype.Timestamptz `json:"claimed_at"`
ReceivedAt pgtype.Timestamptz `json:"received_at"`
Signed bool `json:"signed"`
}
// The claims the observer has stored: at most one of its own and one foreign, normally one in all. Read under
// LockPollingSeats to decide whether a new claim may replace them.
func (q *Queries) ObserverClaimRows(ctx context.Context, observerPublicKey []byte) ([]ObserverClaimRowsRow, error) {
rows, err := q.db.Query(ctx, observerClaimRows, observerPublicKey)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ObserverClaimRowsRow{}
for rows.Next() {
var i ObserverClaimRowsRow
if err := rows.Scan(
&i.IsForeign,
&i.ClaimedAt,
&i.ReceivedAt,
&i.Signed,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const oldestTargetRequest = `-- name: OldestTargetRequest :one
SELECT min(created_at)::timestamptz AS oldest FROM telemetry_requests WHERE target_public_key = $1
`
func (q *Queries) OldestTargetRequest(ctx context.Context, targetPublicKey []byte) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, oldestTargetRequest, targetPublicKey)
var oldest pgtype.Timestamptz
err := row.Scan(&oldest)
return oldest, err
}
const pollingAdminTargetRows = `-- name: PollingAdminTargetRows :many
SELECT k.target_public_key::bytea AS target_public_key, k.observer_public_key::bytea AS observer_public_key,
COALESCE(a.rank, -1)::int AS rank, a.evidence_snr, COALESCE(a.evidence_count, 0)::int AS evidence_count,
COALESCE(c.key_mode, '')::text AS key_mode, COALESCE(c.state, '')::text AS state,
COALESCE(c.misses, 0)::int AS misses, c.last_ok, COALESCE(po.approved, false) AS approved
FROM (
SELECT c.target_public_key, c.observer_public_key FROM polling_candidates c
JOIN polling_claims cl ON cl.observer_public_key = c.observer_public_key
WHERE c.target_public_key = ANY($1::bytea[]) AND cl.received_at > $2
UNION
SELECT a.target_public_key, a.observer_public_key FROM polling_assignments a
WHERE a.target_public_key = ANY($1::bytea[])
) k
LEFT JOIN (
SELECT lc.target_public_key, lc.observer_public_key, lc.key_mode, lc.state, lc.misses, lc.last_ok
FROM polling_candidates lc
JOIN polling_claims lcl ON lcl.observer_public_key = lc.observer_public_key
WHERE lc.target_public_key = ANY($1::bytea[]) AND lcl.received_at > $2
) c ON c.target_public_key = k.target_public_key AND c.observer_public_key = k.observer_public_key
LEFT JOIN polling_assignments a ON a.target_public_key = k.target_public_key AND a.observer_public_key = k.observer_public_key
LEFT JOIN polling_observers po ON po.observer_public_key = k.observer_public_key
ORDER BY k.target_public_key, COALESCE(a.rank, 32767), k.observer_public_key
`
type PollingAdminTargetRowsParams struct {
Targets [][]byte `json:"targets"`
ReceivedAfter pgtype.Timestamptz `json:"received_after"`
}
type PollingAdminTargetRowsRow struct {
TargetPublicKey []byte `json:"target_public_key"`
ObserverPublicKey []byte `json:"observer_public_key"`
Rank int32 `json:"rank"`
EvidenceSnr *float32 `json:"evidence_snr"`
EvidenceCount int32 `json:"evidence_count"`
KeyMode string `json:"key_mode"`
State string `json:"state"`
Misses int32 `json:"misses"`
LastOk pgtype.Timestamptz `json:"last_ok"`
Approved bool `json:"approved"`
}
// Each live candidate and each assigned observer of the given targets. rank is -1 for an unassigned candidate.
// Claim fields come only from a live claim, so an assignment left over from an expired one shows them empty.
func (q *Queries) PollingAdminTargetRows(ctx context.Context, arg PollingAdminTargetRowsParams) ([]PollingAdminTargetRowsRow, error) {
rows, err := q.db.Query(ctx, pollingAdminTargetRows, arg.Targets, arg.ReceivedAfter)
if err != nil {
return nil, err
}
defer rows.Close()
items := []PollingAdminTargetRowsRow{}
for rows.Next() {
var i PollingAdminTargetRowsRow
if err := rows.Scan(
&i.TargetPublicKey,
&i.ObserverPublicKey,
&i.Rank,
&i.EvidenceSnr,
&i.EvidenceCount,
&i.KeyMode,
&i.State,
&i.Misses,
&i.LastOk,
&i.Approved,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const pollingAdminTargets = `-- name: PollingAdminTargets :many
WITH t AS (
SELECT c.target_public_key, max(cl.received_at) AS newest_claim
FROM polling_candidates c
JOIN polling_claims cl ON cl.observer_public_key = c.observer_public_key
WHERE cl.received_at > $1
GROUP BY c.target_public_key
UNION ALL
SELECT a.target_public_key, NULL::timestamptz FROM polling_assignments a GROUP BY a.target_public_key
UNION ALL
SELECT r.target_public_key, NULL::timestamptz FROM telemetry_requests r GROUP BY r.target_public_key
), picked AS (
SELECT t.target_public_key, max(t.newest_claim) AS newest_claim FROM t
GROUP BY t.target_public_key
ORDER BY max(t.newest_claim) DESC NULLS LAST, t.target_public_key
LIMIT $2
)
SELECT p.target_public_key::bytea AS target_public_key,
(SELECT max(l.sampled_at) FROM polling_assignments x
CROSS JOIN LATERAL (
SELECT r.sampled_at FROM repeater_readings r
WHERE r.target_public_key = x.target_public_key AND r.observer_public_key = x.observer_public_key
ORDER BY r.sampled_at DESC LIMIT 1) l
WHERE x.target_public_key = p.target_public_key AND x.evidence_count > 0)::timestamptz AS latest_trusted,
(SELECT r.sampled_at FROM repeater_readings r WHERE r.target_public_key = p.target_public_key
ORDER BY r.sampled_at DESC LIMIT 1)::timestamptz AS latest_any
FROM picked p
ORDER BY p.newest_claim DESC NULLS LAST, p.target_public_key
`
type PollingAdminTargetsParams struct {
ReceivedAfter pgtype.Timestamptz `json:"received_after"`
RowLimit int32 `json:"row_limit"`
}
type PollingAdminTargetsRow struct {
TargetPublicKey []byte `json:"target_public_key"`
LatestTrusted pgtype.Timestamptz `json:"latest_trusted"`
LatestAny pgtype.Timestamptz `json:"latest_any"`
}
// Targets with a live candidate or any assignment row, newest claim first. latest_trusted uses the owners rule.
func (q *Queries) PollingAdminTargets(ctx context.Context, arg PollingAdminTargetsParams) ([]PollingAdminTargetsRow, error) {
rows, err := q.db.Query(ctx, pollingAdminTargets, arg.ReceivedAfter, arg.RowLimit)
if err != nil {
return nil, err
}
defer rows.Close()
items := []PollingAdminTargetsRow{}
for rows.Next() {
var i PollingAdminTargetsRow
if err := rows.Scan(&i.TargetPublicKey, &i.LatestTrusted, &i.LatestAny); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const pollingClaimClaimedAt = `-- name: PollingClaimClaimedAt :one
SELECT claimed_at FROM polling_claims WHERE observer_public_key = $1
`
func (q *Queries) PollingClaimClaimedAt(ctx context.Context, observerPublicKey []byte) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, pollingClaimClaimedAt, observerPublicKey)
var claimed_at pgtype.Timestamptz
err := row.Scan(&claimed_at)
return claimed_at, err
}
const pollingClaimReceivedAt = `-- name: PollingClaimReceivedAt :one
SELECT received_at FROM polling_claims WHERE observer_public_key = $1
`
func (q *Queries) PollingClaimReceivedAt(ctx context.Context, observerPublicKey []byte) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, pollingClaimReceivedAt, observerPublicKey)
var received_at pgtype.Timestamptz
err := row.Scan(&received_at)
return received_at, err
}
const pollingElectionUnlock = `-- name: PollingElectionUnlock :exec
SELECT pg_advisory_unlock(25189, 2)
`
func (q *Queries) PollingElectionUnlock(ctx context.Context) error {
_, err := q.db.Exec(ctx, pollingElectionUnlock)
return err
}
const pollingObserverFlags = `-- name: PollingObserverFlags :one
SELECT blocked, approved FROM polling_observers WHERE observer_public_key = $1
`
type PollingObserverFlagsRow struct {
Blocked bool `json:"blocked"`
Approved bool `json:"approved"`
}
func (q *Queries) PollingObserverFlags(ctx context.Context, observerPublicKey []byte) (PollingObserverFlagsRow, error) {
row := q.db.QueryRow(ctx, pollingObserverFlags, observerPublicKey)
var i PollingObserverFlagsRow
err := row.Scan(&i.Blocked, &i.Approved)
return i, err
}
const pollingOwnerRows = `-- name: PollingOwnerRows :many
WITH mine AS (
SELECT c.target_public_key FROM polling_candidates c WHERE c.observer_public_key = $2
UNION
SELECT a.target_public_key FROM polling_assignments a
WHERE a.observer_public_key = $2 AND a.requested
)
SELECT m.target_public_key::bytea AS target_public_key, COALESCE(a.rank, -1)::int AS rank,
(SELECT count(*) FROM polling_assignments x WHERE x.target_public_key = m.target_public_key)::int AS assigned,
(SELECT max(l.sampled_at) FROM polling_assignments t
CROSS JOIN LATERAL (
SELECT r.sampled_at FROM repeater_readings r
WHERE r.target_public_key = t.target_public_key AND r.observer_public_key = t.observer_public_key
AND NOT r.foreign_source
ORDER BY r.sampled_at DESC LIMIT 1) l
WHERE t.target_public_key = m.target_public_key AND t.evidence_count > 0)::timestamptz AS latest_ts,
COALESCE(a.requested, false)::boolean AS requested,
COALESCE(pc.requested, false)::boolean AS claimed_requested,
EXISTS (SELECT 1 FROM polling_targets pt
WHERE pt.target_public_key = m.target_public_key AND pt.active_request_id IS NOT NULL) AS target_requested,
cl.accepts_requests, cl.request_slots::int AS request_slots, COALESCE(cl.max_slots, 0)::int AS max_slots,
COALESCE(po.approved, false)::boolean AS observer_approved, COALESCE(po.blocked, false)::boolean AS observer_blocked,
pr.id AS request_id, pt.ver AS password_ver, pr.password_ct, pr.password_nonce,
EXISTS (SELECT 1 FROM observers o
WHERE o.public_key = m.target_public_key AND o.last_status_at >= $1) AS target_is_observer
FROM mine m
JOIN polling_claims cl ON cl.observer_public_key = $2
LEFT JOIN polling_observers po ON po.observer_public_key = cl.observer_public_key
LEFT JOIN polling_candidates pc ON pc.observer_public_key = cl.observer_public_key AND pc.target_public_key = m.target_public_key
LEFT JOIN polling_assignments a ON a.target_public_key = m.target_public_key AND a.observer_public_key = cl.observer_public_key
LEFT JOIN polling_targets pt ON pt.target_public_key = m.target_public_key
AND a.requested AND cl.accepts_requests AND NOT COALESCE(po.blocked, false)
LEFT JOIN telemetry_requests pr ON pr.id = pt.active_request_id
WHERE cl.received_at > $3
ORDER BY m.target_public_key
`
type PollingOwnerRowsParams struct {
StatusAfter pgtype.Timestamptz `json:"status_after"`
ObserverPublicKey []byte `json:"observer_public_key"`
ReceivedAt pgtype.Timestamptz `json:"received_at"`
}
type PollingOwnerRowsRow struct {
TargetPublicKey []byte `json:"target_public_key"`
Rank int32 `json:"rank"`
Assigned int32 `json:"assigned"`
LatestTs pgtype.Timestamptz `json:"latest_ts"`
Requested bool `json:"requested"`
ClaimedRequested bool `json:"claimed_requested"`
TargetRequested bool `json:"target_requested"`
AcceptsRequests bool `json:"accepts_requests"`
RequestSlots int32 `json:"request_slots"`
MaxSlots int32 `json:"max_slots"`
ObserverApproved bool `json:"observer_approved"`
ObserverBlocked bool `json:"observer_blocked"`
RequestID pgtype.UUID `json:"request_id"`
PasswordVer *int64 `json:"password_ver"`
PasswordCt []byte `json:"password_ct"`
PasswordNonce []byte `json:"password_nonce"`
TargetIsObserver bool `json:"target_is_observer"`
}
// assigned counts the target's assignment rows. latest_ts only trusts readings from an assigned observer with
// advert evidence (the newest per assignee, then the newest of those), so an observer Beacon has never heard the repeater through cannot stand others down. A target the
// observer was handed as a requested one is listed even before its claim names it (that is how it learns of it);
// claimed_requested is true when the claim names it as requested; target_requested when a request is in use for it.
// accepts_requests, request_slots and max_slots (0 when the claim gave none) are the claim's, for polling.OfferSeats. The observer's flags and the password
// in use come from the same statement, so an answer never pairs a password with an approval it did not exist under.
// The password is only read for a requested assignment of an unblocked observer whose claim accepts requests.
func (q *Queries) PollingOwnerRows(ctx context.Context, arg PollingOwnerRowsParams) ([]PollingOwnerRowsRow, error) {
rows, err := q.db.Query(ctx, pollingOwnerRows, arg.StatusAfter, arg.ObserverPublicKey, arg.ReceivedAt)
if err != nil {
return nil, err
}
defer rows.Close()
items := []PollingOwnerRowsRow{}
for rows.Next() {
var i PollingOwnerRowsRow
if err := rows.Scan(
&i.TargetPublicKey,
&i.Rank,
&i.Assigned,
&i.LatestTs,
&i.Requested,
&i.ClaimedRequested,
&i.TargetRequested,
&i.AcceptsRequests,
&i.RequestSlots,
&i.MaxSlots,
&i.ObserverApproved,
&i.ObserverBlocked,
&i.RequestID,
&i.PasswordVer,
&i.PasswordCt,
&i.PasswordNonce,
&i.TargetIsObserver,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setPollingObserver = `-- name: SetPollingObserver :exec
INSERT INTO polling_observers (observer_public_key, blocked, approved, note) VALUES ($1, $2, $3, $4)
ON CONFLICT (observer_public_key) DO UPDATE SET blocked = EXCLUDED.blocked, approved = EXCLUDED.approved, note = EXCLUDED.note
`
type SetPollingObserverParams struct {
ObserverPublicKey []byte `json:"observer_public_key"`
Blocked bool `json:"blocked"`
Approved bool `json:"approved"`
Note string `json:"note"`
}
func (q *Queries) SetPollingObserver(ctx context.Context, arg SetPollingObserverParams) error {
_, err := q.db.Exec(ctx, setPollingObserver,
arg.ObserverPublicKey,
arg.Blocked,
arg.Approved,
arg.Note,
)
return err
}
const setPollingState = `-- name: SetPollingState :exec
UPDATE polling_state SET paused = $1, paused_until = $2, excluded_nodes = $3 WHERE id
`
type SetPollingStateParams struct {
Paused bool `json:"paused"`
PausedUntil pgtype.Timestamptz `json:"paused_until"`
ExcludedNodes [][]byte `json:"excluded_nodes"`
}
func (q *Queries) SetPollingState(ctx context.Context, arg SetPollingStateParams) error {
_, err := q.db.Exec(ctx, setPollingState, arg.Paused, arg.PausedUntil, arg.ExcludedNodes)
return err
}
const tryPollingElectionLock = `-- name: TryPollingElectionLock :one
SELECT pg_try_advisory_lock(25189, 2)
`
func (q *Queries) TryPollingElectionLock(ctx context.Context) (bool, error) {
row := q.db.QueryRow(ctx, tryPollingElectionLock)
var pg_try_advisory_lock bool
err := row.Scan(&pg_try_advisory_lock)
return pg_try_advisory_lock, err
}
const upsertForeignClaim = `-- name: UpsertForeignClaim :execrows
INSERT INTO polling_foreign_claims (observer_public_key, observer_id, client, poll_host, signed, claimed_at, received_at)
VALUES ($1, $2, $3, $4, $5,
$6, $7)
ON CONFLICT (observer_public_key) DO UPDATE SET
observer_id = EXCLUDED.observer_id, client = EXCLUDED.client, poll_host = EXCLUDED.poll_host, signed = EXCLUDED.signed,
claimed_at = EXCLUDED.claimed_at, received_at = EXCLUDED.received_at
WHERE EXCLUDED.claimed_at > polling_foreign_claims.claimed_at AND polling_foreign_claims.received_at <= $8
`
type UpsertForeignClaimParams struct {
ObserverPublicKey []byte `json:"observer_public_key"`
ObserverID uuid.UUID `json:"observer_id"`
Client string `json:"client"`
PollHost string `json:"poll_host"`
Signed bool `json:"signed"`
ClaimedAt pgtype.Timestamptz `json:"claimed_at"`
ReceivedAt pgtype.Timestamptz `json:"received_at"`
PreviousReceivedBy pgtype.Timestamptz `json:"previous_received_by"`
}
// The same newer-and-not-too-soon rule as UpsertPollingClaim.
func (q *Queries) UpsertForeignClaim(ctx context.Context, arg UpsertForeignClaimParams) (int64, error) {
result, err := q.db.Exec(ctx, upsertForeignClaim,
arg.ObserverPublicKey,
arg.ObserverID,
arg.Client,
arg.PollHost,
arg.Signed,
arg.ClaimedAt,
arg.ReceivedAt,
arg.PreviousReceivedBy,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const upsertPollingClaim = `-- name: UpsertPollingClaim :execrows
INSERT INTO polling_claims (observer_public_key, observer_id, origin, client, policy_version, community, accepts_requests, request_slots, max_slots, poll_interval, poll_host, signed, claim_policy, claimed_at, received_at)
VALUES ($1, $2, $3, $4, $5,
$6, $7, $8, $9, $10,
$11, $12, $13, $14, $15)
ON CONFLICT (observer_public_key) DO UPDATE SET
observer_id = EXCLUDED.observer_id, origin = EXCLUDED.origin, client = EXCLUDED.client,
policy_version = EXCLUDED.policy_version, community = EXCLUDED.community,
accepts_requests = EXCLUDED.accepts_requests, request_slots = EXCLUDED.request_slots,
max_slots = EXCLUDED.max_slots, poll_interval = EXCLUDED.poll_interval,
poll_host = EXCLUDED.poll_host, signed = EXCLUDED.signed, claim_policy = EXCLUDED.claim_policy,
claimed_at = EXCLUDED.claimed_at, received_at = EXCLUDED.received_at
WHERE EXCLUDED.claimed_at > polling_claims.claimed_at AND polling_claims.received_at <= $16
`
type UpsertPollingClaimParams struct {
ObserverPublicKey []byte `json:"observer_public_key"`
ObserverID uuid.UUID `json:"observer_id"`
Origin string `json:"origin"`
Client string `json:"client"`
PolicyVersion string `json:"policy_version"`
Community bool `json:"community"`
AcceptsRequests bool `json:"accepts_requests"`
RequestSlots int16 `json:"request_slots"`
MaxSlots *int16 `json:"max_slots"`
PollInterval *int32 `json:"poll_interval"`
PollHost string `json:"poll_host"`
Signed bool `json:"signed"`
ClaimPolicy string `json:"claim_policy"`
ClaimedAt pgtype.Timestamptz `json:"claimed_at"`
ReceivedAt pgtype.Timestamptz `json:"received_at"`
PreviousReceivedBy pgtype.Timestamptz `json:"previous_received_by"`
}
// Applies only a claim newer than the stored one and received at least the claim interval after it, checked in
// this statement so concurrent claims cannot both pass. Zero rows means it was ignored.
func (q *Queries) UpsertPollingClaim(ctx context.Context, arg UpsertPollingClaimParams) (int64, error) {
result, err := q.db.Exec(ctx, upsertPollingClaim,
arg.ObserverPublicKey,
arg.ObserverID,
arg.Origin,
arg.Client,
arg.PolicyVersion,
arg.Community,
arg.AcceptsRequests,
arg.RequestSlots,
arg.MaxSlots,
arg.PollInterval,
arg.PollHost,
arg.Signed,
arg.ClaimPolicy,
arg.ClaimedAt,
arg.ReceivedAt,
arg.PreviousReceivedBy,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}