Files
beacon-server/db/sqlc/polling.sql.go
T
MrAlders0n 24da3c187d fix(api): count a poller's free seats honestly and read it in one statement
slots.free is 0 when the claim is expired or takes no requests, and no longer
counts seats already handed to the observer that its claim does not name yet.

The claim and its targets were three statements, so a claim replaced between
them gave one claim's slots with the other's targets. They are one statement
now, as the Atlas read is.
2026-11-27 20:05:21 -05:00

1565 lines
60 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 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 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 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 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 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 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,
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, packet_hash, client, 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,
-- Same rule as latest_ts in PollingOwnerRows, frozen at insert time.
EXISTS (
SELECT 1 FROM polling_assignments t
WHERE t.target_public_key = $1 AND t.observer_public_key = $2
AND t.evidence_count > 0
)
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 > $31
) AND (
SELECT count(*) FROM repeater_readings b
WHERE b.observer_public_key = $2 AND b.received_at > $32
) < $33::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"`
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"`
PacketHash []byte `json:"packet_hash"`
Client string `json:"client"`
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.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.PacketHash,
arg.Client,
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 WHERE observer_public_key = $1)
`
func (q *Queries) IsPollerKey(ctx context.Context, observerPublicKey []byte) (bool, error) {
row := q.db.QueryRow(ctx, isPollerKey, observerPublicKey)
var exists bool
err := row.Scan(&exists)
return exists, 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, 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
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"`
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"`
}
// 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.BatteryMv,
&i.TemperatureC,
&i.NoiseFloor,
&i.LastRssi,
&i.LastSnr,
&i.UptimeSecs,
&i.TxQueue,
&i.TxAirSecs,
&i.RxAirSecs,
&i.PacketsRecv,
&i.PacketsSent,
&i.RecvErrors,
); 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, 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
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"`
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"`
}
// 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.BatteryMv,
&i.TemperatureC,
&i.NoiseFloor,
&i.LastRssi,
&i.LastSnr,
&i.UptimeSecs,
&i.TxQueue,
&i.TxAirSecs,
&i.RxAirSecs,
&i.PacketsRecv,
&i.PacketsSent,
&i.RecvErrors,
); err != nil {
return nil, err
}
items = append(items, i)
}
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,
(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"`
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.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 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 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,
(SELECT count(*) FROM repeater_readings r
WHERE r.observer_public_key = p.observer_public_key AND r.received_at > $1)::int AS 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
WHERE p.observer_public_key = $2
)
SELECT cl.received_at, cl.accepts_requests, cl.request_slots, cl.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,
(SELECT r.sampled_at 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)::timestamptz AS latest_reading_at
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
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"`
Readings int32 `json:"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"`
}
// 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. 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.Readings,
&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,
); 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 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 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
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(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"`
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 and request_slots 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.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 upsertPollingClaim = `-- name: UpsertPollingClaim :execrows
INSERT INTO polling_claims (observer_public_key, observer_id, origin, client, policy_version, community, accepts_requests, request_slots, claimed_at, received_at)
VALUES ($1, $2, $3, $4, $5,
$6, $7, $8, $9, $10)
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,
claimed_at = EXCLUDED.claimed_at, received_at = EXCLUDED.received_at
WHERE EXCLUDED.claimed_at > polling_claims.claimed_at AND polling_claims.received_at <= $11
`
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"`
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.ClaimedAt,
arg.ReceivedAt,
arg.PreviousReceivedBy,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}