mirror of
https://github.com/MeshCore-Beacon/beacon-server.git
synced 2026-12-06 16:44:20 +00:00
744 lines
27 KiB
Go
744 lines
27 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 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.id DESC 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.
|
|
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 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 deleteOrphanPollingAssignments = `-- name: DeleteOrphanPollingAssignments :exec
|
|
DELETE 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
|
|
)
|
|
`
|
|
|
|
func (q *Queries) DeleteOrphanPollingAssignments(ctx context.Context) error {
|
|
_, err := q.db.Exec(ctx, deleteOrphanPollingAssignments)
|
|
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)
|
|
VALUES ($1, $2, $3, $4, $5, $6)
|
|
`
|
|
|
|
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"`
|
|
}
|
|
|
|
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,
|
|
)
|
|
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)
|
|
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
|
|
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
|
|
)
|
|
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"`
|
|
}
|
|
|
|
// Inserts nothing when this observer stored a reading of the target by the same method received after recent_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,
|
|
)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return result.RowsAffected(), nil
|
|
}
|
|
|
|
const listPollingCandidates = `-- name: ListPollingCandidates :many
|
|
SELECT c.observer_public_key, c.claimed_snr, c.state, c.misses,
|
|
COALESCE(po.blocked, false) AS blocked,
|
|
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"`
|
|
Blocked bool `json:"blocked"`
|
|
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.Blocked,
|
|
&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
|
|
UNION
|
|
SELECT a.target_public_key FROM polling_assignments a
|
|
) t
|
|
ORDER BY target_public_key
|
|
`
|
|
|
|
// A target with only expired claims is still listed while it has assignment rows, so the caller can clear them.
|
|
func (q *Queries) ListPollingTargets(ctx context.Context, receivedAt pgtype.Timestamptz) ([][]byte, error) {
|
|
rows, err := q.db.Query(ctx, listPollingTargets, receivedAt)
|
|
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 lockPollingTarget = `-- name: LockPollingTarget :exec
|
|
SELECT pg_advisory_xact_lock(hashtextextended(encode($1::bytea, 'hex'), 25190))
|
|
`
|
|
|
|
// Serializes elections of one target until the transaction ends. The one-bigint key space is separate from the
|
|
// (25189, n) two-key locks the rollup and election jobs hold.
|
|
func (q *Queries) LockPollingTarget(ctx context.Context, targetPublicKey []byte) error {
|
|
_, err := q.db.Exec(ctx, lockPollingTarget, targetPublicKey)
|
|
return 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
|
|
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 polling_candidates 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
|
|
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"`
|
|
}
|
|
|
|
// Each live candidate and each assigned observer of the given targets. rank is -1 for an unassigned candidate.
|
|
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,
|
|
); 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
|
|
), 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 r.sampled_at FROM repeater_readings r
|
|
JOIN polling_assignments x ON x.target_public_key = r.target_public_key AND x.observer_public_key = r.observer_public_key
|
|
WHERE r.target_public_key = p.target_public_key AND (x.rank = 0 OR x.evidence_count > 0)
|
|
ORDER BY r.sampled_at DESC LIMIT 1)::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
|
|
SELECT c.target_public_key, COALESCE(a.rank, -1)::int AS rank,
|
|
(SELECT count(*) FROM polling_assignments x WHERE x.target_public_key = c.target_public_key)::int AS assigned,
|
|
(SELECT r.sampled_at FROM repeater_readings r
|
|
JOIN polling_assignments t ON t.target_public_key = r.target_public_key AND t.observer_public_key = r.observer_public_key
|
|
WHERE r.target_public_key = c.target_public_key AND (t.rank = 0 OR t.evidence_count > 0)
|
|
ORDER BY r.sampled_at DESC LIMIT 1)::timestamptz AS latest_ts
|
|
FROM polling_candidates c
|
|
JOIN polling_claims cl ON cl.observer_public_key = c.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
|
|
WHERE c.observer_public_key = $1 AND cl.received_at > $2
|
|
ORDER BY c.target_public_key
|
|
`
|
|
|
|
type PollingOwnerRowsParams struct {
|
|
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"`
|
|
}
|
|
|
|
// assigned counts the target's assignment rows. latest_ts only trusts readings from an assigned observer that is
|
|
// rank 0 or has advert evidence, so a bystander's readings cannot stand the real pollers down.
|
|
func (q *Queries) PollingOwnerRows(ctx context.Context, arg PollingOwnerRowsParams) ([]PollingOwnerRowsRow, error) {
|
|
rows, err := q.db.Query(ctx, pollingOwnerRows, 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,
|
|
); 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
|
|
`
|
|
|
|
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"`
|
|
}
|
|
|
|
// Only a newer claim replaces the stored one; 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,
|
|
)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return result.RowsAffected(), nil
|
|
}
|