mirror of
https://github.com/MeshCore-Beacon/beacon-server.git
synced 2026-12-06 22:34:08 +00:00
A repeater read by a poller this server does not assign now counts as polled while a trusted reading is under 36 hours old. gone_quiet takes 3 and 6 hours on every radio.
744 lines
25 KiB
Go
744 lines
25 KiB
Go
// Code generated by sqlc. DO NOT EDIT.
|
|
// versions:
|
|
// sqlc v1.31.1
|
|
// source: alerts_eval.sql
|
|
|
|
package db
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
)
|
|
|
|
const alertNodeDayAgo = `-- name: AlertNodeDayAgo :many
|
|
SELECT t.k::bytea AS target_public_key, r.sampled_at, r.battery_mv
|
|
FROM unnest($1::bytea[]) AS t(k)
|
|
CROSS JOIN LATERAL (
|
|
SELECT max(x.sampled_at) AS newest FROM repeater_readings x
|
|
WHERE x.target_public_key = t.k AND x.trusted AND x.battery_mv IS NOT NULL AND x.sampled_at >= $2
|
|
) l
|
|
CROSS JOIN LATERAL (
|
|
SELECT y.sampled_at, y.battery_mv FROM repeater_readings y
|
|
WHERE y.target_public_key = t.k AND y.trusted AND y.battery_mv IS NOT NULL
|
|
AND y.sampled_at BETWEEN l.newest - interval '27 hours' AND l.newest - interval '21 hours'
|
|
ORDER BY abs(extract(epoch FROM y.sampled_at - (l.newest - interval '24 hours')))
|
|
LIMIT 1
|
|
) r
|
|
`
|
|
|
|
type AlertNodeDayAgoParams struct {
|
|
Keys [][]byte `json:"keys"`
|
|
Since pgtype.Timestamptz `json:"since"`
|
|
}
|
|
|
|
type AlertNodeDayAgoRow struct {
|
|
TargetPublicKey []byte `json:"target_public_key"`
|
|
SampledAt pgtype.Timestamptz `json:"sampled_at"`
|
|
BatteryMv *int32 `json:"battery_mv"`
|
|
}
|
|
|
|
// For each repeater, the battery reading closest to 24 hours before its newest one, within 3 hours of that mark.
|
|
func (q *Queries) AlertNodeDayAgo(ctx context.Context, arg AlertNodeDayAgoParams) ([]AlertNodeDayAgoRow, error) {
|
|
rows, err := q.db.Query(ctx, alertNodeDayAgo, arg.Keys, arg.Since)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []AlertNodeDayAgoRow{}
|
|
for rows.Next() {
|
|
var i AlertNodeDayAgoRow
|
|
if err := rows.Scan(&i.TargetPublicKey, &i.SampledAt, &i.BatteryMv); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const alertNodeDrifts = `-- name: AlertNodeDrifts :many
|
|
SELECT t.k::bytea AS target_public_key, r.advert_at, r.drift_seconds
|
|
FROM unnest($1::bytea[]) WITH ORDINALITY AS t(k, n)
|
|
CROSS JOIN LATERAL (SELECT ($2::timestamptz[])[t.n] AS c) cur
|
|
CROSS JOIN LATERAL (
|
|
(SELECT d.advert_at, d.drift_seconds FROM node_clock_drifts d JOIN nodes nn ON nn.id = d.node_id
|
|
WHERE nn.public_key = t.k AND d.advert_at <= cur.c ORDER BY d.advert_at DESC LIMIT 1)
|
|
UNION ALL
|
|
(SELECT d.advert_at, d.drift_seconds FROM node_clock_drifts d JOIN nodes nn ON nn.id = d.node_id
|
|
WHERE nn.public_key = t.k AND d.advert_at > cur.c ORDER BY d.advert_at)
|
|
) r
|
|
`
|
|
|
|
type AlertNodeDriftsParams struct {
|
|
Keys [][]byte `json:"keys"`
|
|
Cursors []pgtype.Timestamptz `json:"cursors"`
|
|
}
|
|
|
|
type AlertNodeDriftsRow struct {
|
|
TargetPublicKey []byte `json:"target_public_key"`
|
|
AdvertAt pgtype.Timestamptz `json:"advert_at"`
|
|
DriftSeconds int64 `json:"drift_seconds"`
|
|
}
|
|
|
|
// For each repeater and the oldest cursor of its clock rule: the advert drift at or before the cursor (the pair's
|
|
// first half), then every kept advert after it, oldest first. The table keeps at most 16 per node.
|
|
func (q *Queries) AlertNodeDrifts(ctx context.Context, arg AlertNodeDriftsParams) ([]AlertNodeDriftsRow, error) {
|
|
rows, err := q.db.Query(ctx, alertNodeDrifts, arg.Keys, arg.Cursors)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []AlertNodeDriftsRow{}
|
|
for rows.Next() {
|
|
var i AlertNodeDriftsRow
|
|
if err := rows.Scan(&i.TargetPublicKey, &i.AdvertAt, &i.DriftSeconds); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const alertNodeReadings = `-- name: AlertNodeReadings :many
|
|
SELECT t.k::bytea AS target_public_key, r.sampled_at, r.battery_mv, r.temperature_c, r.noise_floor, r.uptime_secs
|
|
FROM unnest($1::bytea[]) AS t(k)
|
|
CROSS JOIN LATERAL (
|
|
SELECT x.sampled_at, x.battery_mv, x.temperature_c, x.noise_floor, x.uptime_secs
|
|
FROM repeater_readings x
|
|
WHERE x.target_public_key = t.k AND x.trusted AND x.sampled_at >= $2
|
|
ORDER BY x.sampled_at DESC
|
|
LIMIT 12
|
|
) r
|
|
`
|
|
|
|
type AlertNodeReadingsParams struct {
|
|
Keys [][]byte `json:"keys"`
|
|
Since pgtype.Timestamptz `json:"since"`
|
|
}
|
|
|
|
type AlertNodeReadingsRow struct {
|
|
TargetPublicKey []byte `json:"target_public_key"`
|
|
SampledAt pgtype.Timestamptz `json:"sampled_at"`
|
|
BatteryMv *int32 `json:"battery_mv"`
|
|
TemperatureC *float32 `json:"temperature_c"`
|
|
NoiseFloor *int32 `json:"noise_floor"`
|
|
UptimeSecs *int64 `json:"uptime_secs"`
|
|
}
|
|
|
|
// The newest trusted readings of each repeater within the window, at most 12 each.
|
|
func (q *Queries) AlertNodeReadings(ctx context.Context, arg AlertNodeReadingsParams) ([]AlertNodeReadingsRow, error) {
|
|
rows, err := q.db.Query(ctx, alertNodeReadings, arg.Keys, arg.Since)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []AlertNodeReadingsRow{}
|
|
for rows.Next() {
|
|
var i AlertNodeReadingsRow
|
|
if err := rows.Scan(
|
|
&i.TargetPublicKey,
|
|
&i.SampledAt,
|
|
&i.BatteryMv,
|
|
&i.TemperatureC,
|
|
&i.NoiseFloor,
|
|
&i.UptimeSecs,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const alertNodeUptimes = `-- name: AlertNodeUptimes :many
|
|
SELECT t.k::bytea AS target_public_key, r.sampled_at, r.uptime_secs
|
|
FROM unnest($1::bytea[]) WITH ORDINALITY AS t(k, n)
|
|
CROSS JOIN LATERAL (SELECT ($2::timestamptz[])[t.n] AS c) cur
|
|
CROSS JOIN LATERAL (
|
|
(SELECT b.sampled_at, b.uptime_secs FROM repeater_readings b
|
|
WHERE b.target_public_key = t.k AND b.trusted AND b.uptime_secs IS NOT NULL AND b.sampled_at <= cur.c
|
|
ORDER BY b.sampled_at DESC LIMIT 1)
|
|
UNION ALL
|
|
(SELECT a.sampled_at, a.uptime_secs FROM repeater_readings a
|
|
WHERE a.target_public_key = t.k AND a.trusted AND a.uptime_secs IS NOT NULL AND a.sampled_at > cur.c
|
|
ORDER BY a.sampled_at LIMIT $3::int)
|
|
) r
|
|
`
|
|
|
|
type AlertNodeUptimesParams struct {
|
|
Keys [][]byte `json:"keys"`
|
|
Cursors []pgtype.Timestamptz `json:"cursors"`
|
|
PageSize int32 `json:"page_size"`
|
|
}
|
|
|
|
type AlertNodeUptimesRow struct {
|
|
TargetPublicKey []byte `json:"target_public_key"`
|
|
SampledAt pgtype.Timestamptz `json:"sampled_at"`
|
|
UptimeSecs *int64 `json:"uptime_secs"`
|
|
}
|
|
|
|
// For each repeater and the cursor of its reboot rule: the newest trusted uptime reading at or before the cursor (the
|
|
// baseline), then the oldest page_size readings after it, so every reading since the cursor is reached page by page.
|
|
func (q *Queries) AlertNodeUptimes(ctx context.Context, arg AlertNodeUptimesParams) ([]AlertNodeUptimesRow, error) {
|
|
rows, err := q.db.Query(ctx, alertNodeUptimes, arg.Keys, arg.Cursors, arg.PageSize)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []AlertNodeUptimesRow{}
|
|
for rows.Next() {
|
|
var i AlertNodeUptimesRow
|
|
if err := rows.Scan(&i.TargetPublicKey, &i.SampledAt, &i.UptimeSecs); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const alertNodesData = `-- name: AlertNodesData :many
|
|
SELECT n.public_key, COALESCE(n.name, '')::text AS name, n.last_seen, n.last_advert_at, n.device_clock_drift_seconds, n.prev_clock_drift_seconds,
|
|
($1::boolean AND (COALESCE(l.sampled_at >= $2::timestamptz, false)
|
|
OR EXISTS (SELECT 1 FROM polling_assignments a WHERE a.target_public_key = n.public_key)))::boolean AS polled,
|
|
l.sampled_at AS last_reading_at
|
|
FROM nodes n
|
|
LEFT JOIN LATERAL (
|
|
SELECT r.sampled_at FROM repeater_readings r
|
|
WHERE r.target_public_key = n.public_key AND r.trusted
|
|
ORDER BY r.sampled_at DESC LIMIT 1
|
|
) l ON true
|
|
WHERE n.public_key = ANY($3::bytea[])
|
|
`
|
|
|
|
type AlertNodesDataParams struct {
|
|
PollingEnabled bool `json:"polling_enabled"`
|
|
FreshSince pgtype.Timestamptz `json:"fresh_since"`
|
|
Keys [][]byte `json:"keys"`
|
|
}
|
|
|
|
type AlertNodesDataRow struct {
|
|
PublicKey []byte `json:"public_key"`
|
|
Name string `json:"name"`
|
|
LastSeen pgtype.Timestamptz `json:"last_seen"`
|
|
LastAdvertAt pgtype.Timestamptz `json:"last_advert_at"`
|
|
DeviceClockDriftSeconds *int64 `json:"device_clock_drift_seconds"`
|
|
PrevClockDriftSeconds *int64 `json:"prev_clock_drift_seconds"`
|
|
Polled bool `json:"polled"`
|
|
LastReadingAt pgtype.Timestamptz `json:"last_reading_at"`
|
|
}
|
|
|
|
// polled is the same test as the overview's (AlertNodeCaps): while polling is on, a polling assignment or a trusted
|
|
// reading since fresh_since. last_reading_at is the newest trusted reading of any age.
|
|
func (q *Queries) AlertNodesData(ctx context.Context, arg AlertNodesDataParams) ([]AlertNodesDataRow, error) {
|
|
rows, err := q.db.Query(ctx, alertNodesData, arg.PollingEnabled, arg.FreshSince, arg.Keys)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []AlertNodesDataRow{}
|
|
for rows.Next() {
|
|
var i AlertNodesDataRow
|
|
if err := rows.Scan(
|
|
&i.PublicKey,
|
|
&i.Name,
|
|
&i.LastSeen,
|
|
&i.LastAdvertAt,
|
|
&i.DeviceClockDriftSeconds,
|
|
&i.PrevClockDriftSeconds,
|
|
&i.Polled,
|
|
&i.LastReadingAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const alertObserverDayAgo = `-- name: AlertObserverDayAgo :many
|
|
SELECT t.k::uuid AS observer_id, r.reported_at, r.battery_voltage_mv
|
|
FROM unnest($1::uuid[]) AS t(k)
|
|
CROSS JOIN LATERAL (
|
|
SELECT max(x.reported_at) AS newest FROM observer_telemetry x
|
|
WHERE x.observer_id = t.k AND x.battery_voltage_mv IS NOT NULL AND x.reported_at >= $2
|
|
) l
|
|
CROSS JOIN LATERAL (
|
|
SELECT y.reported_at, y.battery_voltage_mv FROM observer_telemetry y
|
|
WHERE y.observer_id = t.k AND y.battery_voltage_mv IS NOT NULL
|
|
AND y.reported_at BETWEEN l.newest - interval '27 hours' AND l.newest - interval '21 hours'
|
|
ORDER BY abs(extract(epoch FROM y.reported_at - (l.newest - interval '24 hours')))
|
|
LIMIT 1
|
|
) r
|
|
`
|
|
|
|
type AlertObserverDayAgoParams struct {
|
|
Ids []uuid.UUID `json:"ids"`
|
|
Since pgtype.Timestamptz `json:"since"`
|
|
}
|
|
|
|
type AlertObserverDayAgoRow struct {
|
|
ObserverID uuid.UUID `json:"observer_id"`
|
|
ReportedAt pgtype.Timestamptz `json:"reported_at"`
|
|
BatteryVoltageMv *int32 `json:"battery_voltage_mv"`
|
|
}
|
|
|
|
func (q *Queries) AlertObserverDayAgo(ctx context.Context, arg AlertObserverDayAgoParams) ([]AlertObserverDayAgoRow, error) {
|
|
rows, err := q.db.Query(ctx, alertObserverDayAgo, arg.Ids, arg.Since)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []AlertObserverDayAgoRow{}
|
|
for rows.Next() {
|
|
var i AlertObserverDayAgoRow
|
|
if err := rows.Scan(&i.ObserverID, &i.ReportedAt, &i.BatteryVoltageMv); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const alertObserverTelemetry = `-- name: AlertObserverTelemetry :many
|
|
SELECT t.k::uuid AS observer_id, r.reported_at, r.battery_voltage_mv, r.noise_floor_db, r.uptime_seconds
|
|
FROM unnest($1::uuid[]) AS t(k)
|
|
CROSS JOIN LATERAL (
|
|
SELECT x.reported_at, x.battery_voltage_mv, x.noise_floor_db, x.uptime_seconds
|
|
FROM observer_telemetry x
|
|
WHERE x.observer_id = t.k AND x.reported_at >= $2
|
|
ORDER BY x.reported_at DESC
|
|
LIMIT 12
|
|
) r
|
|
`
|
|
|
|
type AlertObserverTelemetryParams struct {
|
|
Ids []uuid.UUID `json:"ids"`
|
|
Since pgtype.Timestamptz `json:"since"`
|
|
}
|
|
|
|
type AlertObserverTelemetryRow struct {
|
|
ObserverID uuid.UUID `json:"observer_id"`
|
|
ReportedAt pgtype.Timestamptz `json:"reported_at"`
|
|
BatteryVoltageMv *int32 `json:"battery_voltage_mv"`
|
|
NoiseFloorDb *float32 `json:"noise_floor_db"`
|
|
UptimeSeconds *int64 `json:"uptime_seconds"`
|
|
}
|
|
|
|
func (q *Queries) AlertObserverTelemetry(ctx context.Context, arg AlertObserverTelemetryParams) ([]AlertObserverTelemetryRow, error) {
|
|
rows, err := q.db.Query(ctx, alertObserverTelemetry, arg.Ids, arg.Since)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []AlertObserverTelemetryRow{}
|
|
for rows.Next() {
|
|
var i AlertObserverTelemetryRow
|
|
if err := rows.Scan(
|
|
&i.ObserverID,
|
|
&i.ReportedAt,
|
|
&i.BatteryVoltageMv,
|
|
&i.NoiseFloorDb,
|
|
&i.UptimeSeconds,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const alertObserverUptimes = `-- name: AlertObserverUptimes :many
|
|
SELECT t.k::uuid AS observer_id, r.reported_at, r.uptime_seconds
|
|
FROM unnest($1::uuid[]) WITH ORDINALITY AS t(k, n)
|
|
CROSS JOIN LATERAL (SELECT ($2::timestamptz[])[t.n] AS c) cur
|
|
CROSS JOIN LATERAL (
|
|
(SELECT b.reported_at, b.uptime_seconds FROM observer_telemetry b
|
|
WHERE b.observer_id = t.k AND b.uptime_seconds IS NOT NULL AND b.reported_at <= cur.c
|
|
ORDER BY b.reported_at DESC LIMIT 1)
|
|
UNION ALL
|
|
(SELECT a.reported_at, a.uptime_seconds FROM observer_telemetry a
|
|
WHERE a.observer_id = t.k AND a.uptime_seconds IS NOT NULL AND a.reported_at > cur.c
|
|
ORDER BY a.reported_at LIMIT $3::int)
|
|
) r
|
|
`
|
|
|
|
type AlertObserverUptimesParams struct {
|
|
Ids []uuid.UUID `json:"ids"`
|
|
Cursors []pgtype.Timestamptz `json:"cursors"`
|
|
PageSize int32 `json:"page_size"`
|
|
}
|
|
|
|
type AlertObserverUptimesRow struct {
|
|
ObserverID uuid.UUID `json:"observer_id"`
|
|
ReportedAt pgtype.Timestamptz `json:"reported_at"`
|
|
UptimeSeconds *int64 `json:"uptime_seconds"`
|
|
}
|
|
|
|
// The same for an observer's status telemetry.
|
|
func (q *Queries) AlertObserverUptimes(ctx context.Context, arg AlertObserverUptimesParams) ([]AlertObserverUptimesRow, error) {
|
|
rows, err := q.db.Query(ctx, alertObserverUptimes, arg.Ids, arg.Cursors, arg.PageSize)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []AlertObserverUptimesRow{}
|
|
for rows.Next() {
|
|
var i AlertObserverUptimesRow
|
|
if err := rows.Scan(&i.ObserverID, &i.ReportedAt, &i.UptimeSeconds); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const alertObserversData = `-- name: AlertObserversData :many
|
|
SELECT id, public_key, COALESCE(display_name, '')::text AS name, last_seen, last_status_at,
|
|
EXISTS (SELECT 1 FROM observer_telemetry f WHERE f.observer_id = observers.id AND f.reported_at >= $1) AS polled
|
|
FROM observers WHERE public_key = ANY($2::bytea[])
|
|
`
|
|
|
|
type AlertObserversDataParams struct {
|
|
FreshSince pgtype.Timestamptz `json:"fresh_since"`
|
|
Keys [][]byte `json:"keys"`
|
|
}
|
|
|
|
type AlertObserversDataRow struct {
|
|
ID uuid.UUID `json:"id"`
|
|
PublicKey []byte `json:"public_key"`
|
|
Name string `json:"name"`
|
|
LastSeen pgtype.Timestamptz `json:"last_seen"`
|
|
LastStatusAt pgtype.Timestamptz `json:"last_status_at"`
|
|
Polled bool `json:"polled"`
|
|
}
|
|
|
|
// polled is the same test as the overview's (AlertObserverCaps): status telemetry within fresh_since.
|
|
func (q *Queries) AlertObserversData(ctx context.Context, arg AlertObserversDataParams) ([]AlertObserversDataRow, error) {
|
|
rows, err := q.db.Query(ctx, alertObserversData, arg.FreshSince, arg.Keys)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []AlertObserversDataRow{}
|
|
for rows.Next() {
|
|
var i AlertObserversDataRow
|
|
if err := rows.Scan(
|
|
&i.ID,
|
|
&i.PublicKey,
|
|
&i.Name,
|
|
&i.LastSeen,
|
|
&i.LastStatusAt,
|
|
&i.Polled,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const alertRuleBatch = `-- name: AlertRuleBatch :many
|
|
SELECT r.id, r.user_id, r.target_kind, r.target_public_key, r.kind, r.threshold, r.threshold_high, r.state,
|
|
r.last_sent_at, r.cursor_at, r.streak, r.version,
|
|
COALESCE((SELECT p.name FROM user_atlas_pins p WHERE p.user_id = r.user_id AND p.public_key = r.target_public_key LIMIT 1), '')::text AS pin_name,
|
|
g.recovered_at AS sibling_recovered_at, COALESCE(g.enabled, false)::boolean AS sibling_enabled
|
|
FROM user_alert_rules r
|
|
JOIN users u ON u.id = r.user_id AND u.disabled_at IS NULL
|
|
LEFT JOIN user_alert_rules g ON r.kind = 'back_online' AND g.user_id = r.user_id AND g.target_public_key = r.target_public_key AND g.kind = 'gone_quiet'
|
|
WHERE r.enabled AND r.id > $1::uuid
|
|
ORDER BY r.id
|
|
LIMIT $2
|
|
`
|
|
|
|
type AlertRuleBatchParams struct {
|
|
AfterID uuid.UUID `json:"after_id"`
|
|
RowLimit int32 `json:"row_limit"`
|
|
}
|
|
|
|
type AlertRuleBatchRow struct {
|
|
ID uuid.UUID `json:"id"`
|
|
UserID uuid.UUID `json:"user_id"`
|
|
TargetKind string `json:"target_kind"`
|
|
TargetPublicKey []byte `json:"target_public_key"`
|
|
Kind string `json:"kind"`
|
|
Threshold *int32 `json:"threshold"`
|
|
ThresholdHigh *int32 `json:"threshold_high"`
|
|
State string `json:"state"`
|
|
LastSentAt pgtype.Timestamptz `json:"last_sent_at"`
|
|
CursorAt pgtype.Timestamptz `json:"cursor_at"`
|
|
Streak int16 `json:"streak"`
|
|
Version int64 `json:"version"`
|
|
PinName string `json:"pin_name"`
|
|
SiblingRecoveredAt pgtype.Timestamptz `json:"sibling_recovered_at"`
|
|
SiblingEnabled bool `json:"sibling_enabled"`
|
|
}
|
|
|
|
// The next enabled rules of live users after the id, with the name the user gave the pin and, for a back_online
|
|
// rule, when the radio's gone_quiet rule last recovered and whether that rule is on.
|
|
func (q *Queries) AlertRuleBatch(ctx context.Context, arg AlertRuleBatchParams) ([]AlertRuleBatchRow, error) {
|
|
rows, err := q.db.Query(ctx, alertRuleBatch, arg.AfterID, arg.RowLimit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []AlertRuleBatchRow{}
|
|
for rows.Next() {
|
|
var i AlertRuleBatchRow
|
|
if err := rows.Scan(
|
|
&i.ID,
|
|
&i.UserID,
|
|
&i.TargetKind,
|
|
&i.TargetPublicKey,
|
|
&i.Kind,
|
|
&i.Threshold,
|
|
&i.ThresholdHigh,
|
|
&i.State,
|
|
&i.LastSentAt,
|
|
&i.CursorAt,
|
|
&i.Streak,
|
|
&i.Version,
|
|
&i.PinName,
|
|
&i.SiblingRecoveredAt,
|
|
&i.SiblingEnabled,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const alertsEvalUnlock = `-- name: AlertsEvalUnlock :exec
|
|
SELECT pg_advisory_unlock(25189, 3)
|
|
`
|
|
|
|
func (q *Queries) AlertsEvalUnlock(ctx context.Context) error {
|
|
_, err := q.db.Exec(ctx, alertsEvalUnlock)
|
|
return err
|
|
}
|
|
|
|
const alertsSendUnlock = `-- name: AlertsSendUnlock :exec
|
|
SELECT pg_advisory_unlock(25189, 4)
|
|
`
|
|
|
|
func (q *Queries) AlertsSendUnlock(ctx context.Context) error {
|
|
_, err := q.db.Exec(ctx, alertsSendUnlock)
|
|
return err
|
|
}
|
|
|
|
const applyAlertUpdates = `-- name: ApplyAlertUpdates :many
|
|
UPDATE user_alert_rules r SET
|
|
state = u.state,
|
|
state_changed_at = CASE WHEN r.state <> u.state THEN now() ELSE r.state_changed_at END,
|
|
last_sent_at = COALESCE(u.sent_at, r.last_sent_at),
|
|
cursor_at = u.cursor_at,
|
|
streak = u.streak,
|
|
recovered_at = COALESCE(u.recovered_at, r.recovered_at)
|
|
FROM (SELECT unnest($1::uuid[]) AS id, unnest($2::bigint[]) AS version,
|
|
unnest($3::text[]) AS state, unnest($4::timestamptz[]) AS sent_at,
|
|
unnest($5::timestamptz[]) AS cursor_at, unnest($6::int[]) AS streak,
|
|
unnest($7::timestamptz[]) AS recovered_at) u
|
|
WHERE r.id = u.id AND r.version = u.version
|
|
RETURNING r.id
|
|
`
|
|
|
|
type ApplyAlertUpdatesParams struct {
|
|
Ids []uuid.UUID `json:"ids"`
|
|
Versions []int64 `json:"versions"`
|
|
States []string `json:"states"`
|
|
SentAts []pgtype.Timestamptz `json:"sent_ats"`
|
|
Cursors []pgtype.Timestamptz `json:"cursors"`
|
|
Streaks []int32 `json:"streaks"`
|
|
RecoveredAts []pgtype.Timestamptz `json:"recovered_ats"`
|
|
}
|
|
|
|
// Stores what the evaluation decided, only for rules not edited since they were read (same version). Returns the ids
|
|
// that were stored.
|
|
func (q *Queries) ApplyAlertUpdates(ctx context.Context, arg ApplyAlertUpdatesParams) ([]uuid.UUID, error) {
|
|
rows, err := q.db.Query(ctx, applyAlertUpdates,
|
|
arg.Ids,
|
|
arg.Versions,
|
|
arg.States,
|
|
arg.SentAts,
|
|
arg.Cursors,
|
|
arg.Streaks,
|
|
arg.RecoveredAts,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []uuid.UUID{}
|
|
for rows.Next() {
|
|
var id uuid.UUID
|
|
if err := rows.Scan(&id); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, id)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const dueRequestAttention = `-- name: DueRequestAttention :many
|
|
SELECT r.id, r.user_id, r.target_public_key, r.status, COALESCE(n.name, '')::text AS node_name
|
|
FROM telemetry_requests r
|
|
JOIN users u ON u.id = r.user_id AND u.disabled_at IS NULL
|
|
LEFT JOIN nodes n ON n.public_key = r.target_public_key
|
|
WHERE r.status IN ('login_failed', 'admin_stopped', 'disabled') AND r.attention_status IS DISTINCT FROM r.status
|
|
ORDER BY r.id
|
|
LIMIT 200
|
|
FOR UPDATE OF r SKIP LOCKED
|
|
`
|
|
|
|
type DueRequestAttentionRow struct {
|
|
ID uuid.UUID `json:"id"`
|
|
UserID uuid.UUID `json:"user_id"`
|
|
TargetPublicKey []byte `json:"target_public_key"`
|
|
Status string `json:"status"`
|
|
NodeName string `json:"node_name"`
|
|
}
|
|
|
|
// Telemetry requests that need attention and were not announced at this status, locked until the transaction ends.
|
|
func (q *Queries) DueRequestAttention(ctx context.Context) ([]DueRequestAttentionRow, error) {
|
|
rows, err := q.db.Query(ctx, dueRequestAttention)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
items := []DueRequestAttentionRow{}
|
|
for rows.Next() {
|
|
var i DueRequestAttentionRow
|
|
if err := rows.Scan(
|
|
&i.ID,
|
|
&i.UserID,
|
|
&i.TargetPublicKey,
|
|
&i.Status,
|
|
&i.NodeName,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
const insertAlertNotices = `-- name: InsertAlertNotices :exec
|
|
INSERT INTO alert_outbox (user_id, pass_id, target_kind, target_public_key, name, alert_kind, value, detail)
|
|
SELECT u.user_id, $1::uuid, u.target_kind, u.target_public_key, u.name, u.alert_kind, u.value, u.detail
|
|
FROM (SELECT unnest($2::uuid[]) AS user_id, unnest($3::text[]) AS target_kind,
|
|
unnest($4::bytea[]) AS target_public_key, unnest($5::text[]) AS name,
|
|
unnest($6::text[]) AS alert_kind, unnest($7::bigint[]) AS value,
|
|
unnest($8::text[]) AS detail) u
|
|
`
|
|
|
|
type InsertAlertNoticesParams struct {
|
|
PassID uuid.UUID `json:"pass_id"`
|
|
UserIds []uuid.UUID `json:"user_ids"`
|
|
TargetKinds []string `json:"target_kinds"`
|
|
TargetKeys [][]byte `json:"target_keys"`
|
|
Names []string `json:"names"`
|
|
AlertKinds []string `json:"alert_kinds"`
|
|
Values []int64 `json:"values"`
|
|
Details []string `json:"details"`
|
|
}
|
|
|
|
func (q *Queries) InsertAlertNotices(ctx context.Context, arg InsertAlertNoticesParams) error {
|
|
_, err := q.db.Exec(ctx, insertAlertNotices,
|
|
arg.PassID,
|
|
arg.UserIds,
|
|
arg.TargetKinds,
|
|
arg.TargetKeys,
|
|
arg.Names,
|
|
arg.AlertKinds,
|
|
arg.Values,
|
|
arg.Details,
|
|
)
|
|
return err
|
|
}
|
|
|
|
const markRequestAttention = `-- name: MarkRequestAttention :exec
|
|
UPDATE telemetry_requests t SET attention_status = u.status
|
|
FROM (SELECT unnest($1::uuid[]) AS id, unnest($2::text[]) AS status) u
|
|
WHERE t.id = u.id
|
|
`
|
|
|
|
type MarkRequestAttentionParams struct {
|
|
Ids []uuid.UUID `json:"ids"`
|
|
Statuses []string `json:"statuses"`
|
|
}
|
|
|
|
func (q *Queries) MarkRequestAttention(ctx context.Context, arg MarkRequestAttentionParams) error {
|
|
_, err := q.db.Exec(ctx, markRequestAttention, arg.Ids, arg.Statuses)
|
|
return err
|
|
}
|
|
|
|
const resetRequestAttention = `-- name: ResetRequestAttention :exec
|
|
UPDATE telemetry_requests SET attention_status = NULL
|
|
WHERE attention_status IS NOT NULL AND status NOT IN ('login_failed', 'admin_stopped', 'disabled')
|
|
`
|
|
|
|
// A request that is fine again can be announced again the next time it needs attention.
|
|
func (q *Queries) ResetRequestAttention(ctx context.Context) error {
|
|
_, err := q.db.Exec(ctx, resetRequestAttention)
|
|
return err
|
|
}
|
|
|
|
const tryAlertsEvalLock = `-- name: TryAlertsEvalLock :one
|
|
SELECT pg_try_advisory_lock(25189, 3)
|
|
`
|
|
|
|
func (q *Queries) TryAlertsEvalLock(ctx context.Context) (bool, error) {
|
|
row := q.db.QueryRow(ctx, tryAlertsEvalLock)
|
|
var pg_try_advisory_lock bool
|
|
err := row.Scan(&pg_try_advisory_lock)
|
|
return pg_try_advisory_lock, err
|
|
}
|
|
|
|
const tryAlertsSendLock = `-- name: TryAlertsSendLock :one
|
|
SELECT pg_try_advisory_lock(25189, 4)
|
|
`
|
|
|
|
func (q *Queries) TryAlertsSendLock(ctx context.Context) (bool, error) {
|
|
row := q.db.QueryRow(ctx, tryAlertsSendLock)
|
|
var pg_try_advisory_lock bool
|
|
err := row.Scan(&pg_try_advisory_lock)
|
|
return pg_try_advisory_lock, err
|
|
}
|