perf: load console pages in time for organizations with many monitors
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m10s
ci / test (pull_request) Successful in 12m19s
ci / build (pull_request) Successful in 18m13s
ci / image (pull_request) Successful in 5m20s

Every console page that shows monitor status (monitors, incidents,
monitor details, evidence) went through one loader that read, for all of
the organization's monitors:

- the newest result per monitor and region, by scanning a day of raw
  results;
- the bars of the selected range, from raw results for ranges up to 24h,
  though only one page of monitors is shown;
- when each monitor first reported, scanning two days of results.

With 3000 monitors that took about a second, growing with the number of
results. Now:

- latest_results keeps the newest result per monitor and region,
  updated as results are stored (migration 00055 fills it from the last
  day);
- bars are loaded only for the monitors a page shows;
- first data is loaded per monitor on its page, and the monitor list asks
  only for the organization's earliest data, by index;
- monitor, region and incident queries name the organization, so their
  indexes are used instead of row security filtering whole tables.

Public status pages also read only their own monitors' latest results
and hourly buckets instead of the whole organization's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-26 08:00:38 +01:00
1 parent 2a440b9c5e
commit 1138d555aa
22 files changed
+630 -182

No files matched your search

+1 -2
View File
@@ -337,8 +337,7 @@ func (s *Server) agentResults(c *gin.Context) {
if len(params) == 0 { if len(params) == 0 {
return nil return nil
} }
_, err = q.InsertCheckResults(ctx, params) return insertResults(ctx, q, params)
return err
}) })
if err != nil { if err != nil {
// Unclaimed, the checker's retry is stored instead. // Unclaimed, the checker's retry is stored instead.
+1 -1
View File
@@ -182,7 +182,7 @@ func (s *Server) loadCheckerActivity(ctx context.Context, p *principal, instance
a.Siblings = append(a.Siblings, sb.ID) a.Siblings = append(a.Siblings, sb.ID)
} }
} }
monitors, err := q.ListMonitors(ctx) monitors, err := q.ListMonitors(ctx, p.Org.ID)
if err != nil { if err != nil {
return err return err
} }
+139 -53
View File
@@ -84,12 +84,19 @@ func (s *Server) dashboard(c *gin.Context) {
if !s.dashboardPage(c, &v, data) { if !s.dashboardPage(c, &v, data) {
return return
} }
if err := s.dashboardBars(c.Request.Context(), p, &v, &data); err != nil {
internalError(c, err)
return
}
v.Range = data.rng.Key v.Range = data.rng.Key
var earliest time.Time var earliest time.Time
for _, m := range data.byID { if err := s.db.Tx(c.Request.Context(), p.scope(), func(q *store.Queries) error {
if f, ok := data.first[m.ID]; ok && (earliest.IsZero() || f.Before(earliest)) { var err error
earliest = f earliest, err = earliestData(c.Request.Context(), q, p.Org.ID, data.now)
} return err
}); err != nil {
internalError(c, err)
return
} }
v.Ranges = rangeOptions(c, data.rng, earliest, data.now) v.Ranges = rangeOptions(c, data.rng, earliest, data.now)
for _, m := range data.rows { for _, m := range data.rows {
@@ -107,6 +114,47 @@ func (s *Server) dashboard(c *gin.Context) {
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v)) web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
} }
// dashboardBars loads the bars of the monitors v shows, and only those.
func (s *Server) dashboardBars(ctx context.Context, p *principal, v *web.DashboardView, data *monitorData) error {
var ids []uuid.UUID
walk := func(rows []web.MonitorRow, set bool) {
for i := range rows {
id, err := uuid.Parse(rows[i].ID)
if err != nil {
continue
}
if set {
rows[i].Bars = data.bars(id)
} else {
ids = append(ids, id)
}
}
}
var tree func(n *web.GroupNode, set bool)
tree = func(n *web.GroupNode, set bool) {
walk(n.Monitors, set)
for i := range n.Children {
tree(&n.Children[i], set)
}
}
// A search or filter lists Results instead of the tree.
listing := v.Search != "" || v.Filter != ""
if listing {
walk(v.Results, false)
} else {
tree(&v.Root, false)
}
if err := s.loadBars(ctx, p, data, ids); err != nil {
return err
}
if listing {
walk(v.Results, true)
} else {
tree(&v.Root, true)
}
return nil
}
// groupMonitorsShown is how many of its own monitors a group shows on the // groupMonitorsShown is how many of its own monitors a group shows on the
// dashboard before linking to all of them. // dashboard before linking to all of them.
const groupMonitorsShown = 50 const groupMonitorsShown = 50
@@ -324,80 +372,96 @@ type monitorData struct {
maint map[uuid.UUID][]store.MaintenanceWindow maint map[uuid.UUID][]store.MaintenanceWindow
rows []web.MonitorRow rows []web.MonitorRow
byID map[uuid.UUID]store.Monitor byID map[uuid.UUID]store.Monitor
// buckets cover the selected range at its resolution. // buckets cover the selected range at its resolution, for the
// monitors loadBars was asked for.
buckets map[uuid.UUID][]web.Bucket buckets map[uuid.UUID][]web.Bucket
down map[uuid.UUID][]web.Span down map[uuid.UUID][]web.Span
regionOf map[uuid.UUID]store.Region regionOf map[uuid.UUID]store.Region
rng web.TimeRange rng web.TimeRange
now time.Time now time.Time
// first is when each monitor first reported, from any region; // first is when the monitor of a detail page first reported, from
// firstRegion the same per region. // any region; firstRegion the same per region.
first map[uuid.UUID]time.Time first time.Time
firstRegion map[uuid.UUID]map[string]time.Time firstRegion map[string]time.Time
// statuses are the organization's own incident statuses. // statuses are the organization's own incident statuses.
statuses customStatuses statuses customStatuses
// usedRegions are the regions the enabled monitors are checked from. // usedRegions are the regions the enabled monitors are checked from.
usedRegions []uuid.UUID usedRegions []uuid.UUID
} }
// loadFirstData finds when monitors and their regions first reported. The // loadFirstData finds when monitor and its regions first reported. The
// daily aggregate answers to the day, which is precise enough for anything // daily aggregate answers to the day, which is precise enough for anything
// older than two days; younger data is looked up in the raw results. // older than two days; younger data is looked up exactly.
func loadFirstData(ctx context.Context, q *store.Queries, org uuid.UUID, now time.Time) (map[uuid.UUID]time.Time, map[uuid.UUID]map[string]time.Time, error) { func loadFirstData(ctx context.Context, q *store.Queries, org, monitor uuid.UUID, now time.Time) (time.Time, map[string]time.Time, error) {
first := map[uuid.UUID]time.Time{} var first time.Time
perRegion := map[uuid.UUID]map[string]time.Time{} perRegion := map[string]time.Time{}
note := func(m uuid.UUID, region string, t time.Time) { note := func(region string, t time.Time) {
if perRegion[m] == nil { if cur, ok := perRegion[region]; !ok || t.Before(cur) {
perRegion[m] = map[string]time.Time{} perRegion[region] = t
} }
if cur, ok := perRegion[m][region]; !ok || t.Before(cur) { if first.IsZero() || t.Before(first) {
perRegion[m][region] = t first = t
}
if cur, ok := first[m]; !ok || t.Before(cur) {
first[m] = t
} }
} }
recentSince := now.Add(-2 * 24 * time.Hour) recentSince := now.Add(-2 * 24 * time.Hour)
daily, err := q.FirstDataDaily(ctx, org) daily, err := q.FirstDataDaily(ctx, store.FirstDataDailyParams{OrgID: org, MonitorID: monitor})
if err != nil { if err != nil {
return nil, nil, err return first, nil, err
} }
for _, r := range daily { for _, r := range daily {
if r.First.Before(recentSince) { if r.First.Before(recentSince) {
note(r.MonitorID, r.Region, r.First) note(r.Region, r.First)
} }
} }
recent, err := q.FirstDataRecent(ctx, store.FirstDataRecentParams{OrgID: org, Time: recentSince}) recent, err := q.FirstDataRecent(ctx, store.FirstDataRecentParams{OrgID: org, MonitorID: monitor, Time: recentSince})
if err != nil { if err != nil {
return nil, nil, err return first, nil, err
} }
for _, r := range recent { for _, r := range recent {
note(r.MonitorID, r.Region, r.First) note(r.Region, r.First)
} }
return first, perRegion, nil return first, perRegion, nil
} }
// rangeBuckets loads the selected range for all monitors, or one if // earliestData finds when any monitor of org first reported, for the
// monitor is set. // ranges the monitor list offers: to the day if that was over two days
func rangeBuckets(ctx context.Context, q *store.Queries, org uuid.UUID, monitor *uuid.UUID, rng web.TimeRange, now time.Time) (map[uuid.UUID][]web.Bucket, error) { // ago, otherwise exactly.
func earliestData(ctx context.Context, q *store.Queries, org uuid.UUID, now time.Time) (time.Time, error) {
none := func(t time.Time, err error) (time.Time, bool, error) {
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, false, nil
}
return t, err == nil, err
}
recentSince := now.Add(-2 * 24 * time.Hour)
daily, ok, err := none(q.EarliestDataDaily(ctx, org))
if err != nil || (ok && daily.Before(recentSince)) {
return daily, err
}
exact, _, err := none(q.EarliestDataRecent(ctx, store.EarliestDataRecentParams{OrgID: org, Time: recentSince}))
return exact, err
}
// rangeBuckets loads the selected range for the monitors ids.
func rangeBuckets(ctx context.Context, q *store.Queries, org uuid.UUID, ids []uuid.UUID, rng web.TimeRange, now time.Time) (map[uuid.UUID][]web.Bucket, error) {
out := map[uuid.UUID][]web.Bucket{} out := map[uuid.UUID][]web.Bucket{}
since := now.Add(-rng.Window).Truncate(rng.Bucket) since := now.Add(-rng.Window).Truncate(rng.Bucket)
width := fmt.Sprintf("%d seconds", int(rng.Bucket.Seconds())) width := fmt.Sprintf("%d seconds", int(rng.Bucket.Seconds()))
switch rng.Source { switch rng.Source {
case web.SourceHourly: case web.SourceHourly:
rows, err := q.RangeBucketsHourly(ctx, store.RangeBucketsHourlyParams{OrgID: org, Width: width, Since: since, MonitorID: monitor}) rows, err := q.RangeBucketsHourly(ctx, store.RangeBucketsHourlyParams{OrgID: org, Width: width, Since: since, Ids: ids})
for _, r := range rows { for _, r := range rows {
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs}) out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
} }
return out, err return out, err
case web.SourceDaily: case web.SourceDaily:
rows, err := q.RangeBucketsDaily(ctx, store.RangeBucketsDailyParams{OrgID: org, Width: width, Since: since, MonitorID: monitor}) rows, err := q.RangeBucketsDaily(ctx, store.RangeBucketsDailyParams{OrgID: org, Width: width, Since: since, Ids: ids})
for _, r := range rows { for _, r := range rows {
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs}) out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
} }
return out, err return out, err
} }
rows, err := q.RangeBuckets(ctx, store.RangeBucketsParams{OrgID: org, Width: width, Since: since, MonitorID: monitor}) rows, err := q.RangeBuckets(ctx, store.RangeBucketsParams{OrgID: org, Width: width, Since: since, Ids: ids})
for _, r := range rows { for _, r := range rows {
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs}) out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
} }
@@ -414,9 +478,10 @@ func (d monitorData) slaFor(m store.Monitor, window time.Duration) float64 {
return web.SLA(d.down[m.ID], from, d.now) return web.SLA(d.down[m.ID], from, d.now)
} }
// loadMonitorData assembles everything the monitor list shows. // loadMonitorData assembles the status of every monitor for rng.
// loadMonitorData assembles everything the monitor list shows for rng. // Incidents are loaded far enough back for every SLA window. The bars of
// Incidents are loaded far enough back for every SLA window. // rng are left to loadBars, for the monitors shown: an organization may
// have thousands.
func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.TimeRange) (monitorData, error) { func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.TimeRange) (monitorData, error) {
now := time.Now() now := time.Now()
d := monitorData{ d := monitorData{
@@ -438,10 +503,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
if groups, err = q.ListGroups(ctx); err != nil { if groups, err = q.ListGroups(ctx); err != nil {
return err return err
} }
if monitors, err = q.ListMonitors(ctx); err != nil { if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
return err return err
} }
if assigned, err = q.AllMonitorRegions(ctx); err != nil { if assigned, err = q.AllMonitorRegions(ctx, p.Org.ID); err != nil {
return err return err
} }
if regions, err = q.ListVisibleRegions(ctx); err != nil { if regions, err = q.ListVisibleRegions(ctx); err != nil {
@@ -450,13 +515,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil { if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil {
return err return err
} }
if open, err = q.OpenIncidents(ctx); err != nil { if open, err = q.OpenIncidents(ctx, p.Org.ID); err != nil {
return err return err
} }
if spans, err = q.IncidentsSince(ctx, ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))); err != nil { if spans, err = q.IncidentsSince(ctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
return err
}
if d.first, d.firstRegion, err = loadFirstData(ctx, q, p.Org.ID, now); err != nil {
return err return err
} }
if d.statuses, err = loadCustomStatuses(ctx, q); err != nil { if d.statuses, err = loadCustomStatuses(ctx, q); err != nil {
@@ -466,10 +528,7 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
for i, m := range monitors { for i, m := range monitors {
ids[i] = m.ID ids[i] = m.ID
} }
if d.maint, err = maintenanceFor(ctx, q, ids); err != nil { d.maint, err = maintenanceFor(ctx, q, ids)
return err
}
d.buckets, err = rangeBuckets(ctx, q, p.Org.ID, nil, rng, now)
return err return err
}) })
if err != nil { if err != nil {
@@ -581,7 +640,6 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
} }
row.Ratio = d.slaFor(m, rng.Window) row.Ratio = d.slaFor(m, rng.Window)
row.Uptime = web.SLAText(row.Ratio) row.Uptime = web.SLAText(row.Ratio)
row.Bars = web.UptimeBars(d.buckets[m.ID], now, rng.Bucket, rng.Bars(), rng.Layout)
d.rows = append(d.rows, row) d.rows = append(d.rows, row)
} }
// Problems first, then by name. // Problems first, then by name.
@@ -589,6 +647,23 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
return d, nil return d, nil
} }
// loadBars loads the bars of the selected range for the monitors ids.
func (s *Server) loadBars(ctx context.Context, p *principal, d *monitorData, ids []uuid.UUID) error {
if len(ids) == 0 {
return nil
}
return s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
d.buckets, err = rangeBuckets(ctx, q, p.Org.ID, ids, d.rng, d.now)
return err
})
}
// bars are the monitor's bars of the selected range, from loadBars.
func (d monitorData) bars(id uuid.UUID) []web.Bar {
return web.UptimeBars(d.buckets[id], d.now, d.rng.Bucket, d.rng.Bars(), d.rng.Layout)
}
func (d monitorData) regionName(id uuid.UUID) string { func (d monitorData) regionName(id uuid.UUID) string {
if r, ok := d.regionOf[id]; ok { if r, ok := d.regionOf[id]; ok {
return r.Name return r.Name
@@ -611,6 +686,16 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
if !ok { if !ok {
return notFoundPage(c) return notFoundPage(c)
} }
if err := s.loadBars(ctx, p, &d, []uuid.UUID{id}); err != nil {
return nil, err
}
if err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
d.first, d.firstRegion, err = loadFirstData(ctx, q, p.Org.ID, id, d.now)
return err
}); err != nil {
return nil, err
}
v := web.MonitorDetailView{ v := web.MonitorDetailView{
Interval: (time.Duration(m.IntervalSeconds) * time.Second).String(), Interval: (time.Duration(m.IntervalSeconds) * time.Second).String(),
PingURL: s.detailPingURL(p, d, m), PingURL: s.detailPingURL(p, d, m),
@@ -618,7 +703,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
Latency: web.Latency(d.buckets[id], d.now.Add(-d.rng.Window).Truncate(d.rng.Bucket), d.now, 480, 96), Latency: web.Latency(d.buckets[id], d.now.Add(-d.rng.Window).Truncate(d.rng.Bucket), d.now, 480, 96),
Maintenance: maintenanceItems(d.maint[id], d.now), Maintenance: maintenanceItems(d.maint[id], d.now),
Range: d.rng.Key, Range: d.rng.Key,
Ranges: rangeOptions(c, d.rng, d.first[id], d.now), Ranges: rangeOptions(c, d.rng, d.first, d.now),
Uptime90: "–", Uptime90: "–",
} }
for _, r := range d.rows { for _, r := range d.rows {
@@ -626,6 +711,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
v.Row = r v.Row = r
} }
} }
v.Row.Bars = d.bars(id)
var ( var (
daily []store.DailyBucketsRow daily []store.DailyBucketsRow
recent []store.ListResultsRow recent []store.ListResultsRow
@@ -654,7 +740,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
for _, w := range web.SLAWindows { for _, w := range web.SLAWindows {
v.SLAs = append(v.SLAs, web.SLAEntry{ v.SLAs = append(v.SLAs, web.SLAEntry{
Label: w.Key, Value: web.SLAText(d.slaFor(m, w.Window)), Label: w.Key, Value: web.SLAText(d.slaFor(m, w.Window)),
Partial: !web.HasEnoughData(d.first[id], d.now, w.Window), Partial: !web.HasEnoughData(d.first, d.now, w.Window),
}) })
} }
regions, err := s.regionHistory(ctx, p, d, m) regions, err := s.regionHistory(ctx, p, d, m)
@@ -1248,7 +1334,7 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
if orgGroups, err = q.ListGroups(ctx); err != nil { if orgGroups, err = q.ListGroups(ctx); err != nil {
return err return err
} }
if monitors, err = q.ListMonitors(ctx); err != nil { if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
return err return err
} }
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID) own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
@@ -1479,7 +1565,7 @@ func (s *Server) regionHistory(ctx context.Context, p *principal, d monitorData,
Name: d.regionNameString(r), Name: d.regionNameString(r),
Bars: web.UptimeBars(byRegion[r], d.now, rng.Bucket, rng.Bars(), rng.Layout), Bars: web.UptimeBars(byRegion[r], d.now, rng.Bucket, rng.Bars(), rng.Layout),
Uptime: "–", Uptime: "–",
Enough: web.HasEnoughData(d.firstRegion[m.ID][r], d.now, rng.Window), Enough: web.HasEnoughData(d.firstRegion[r], d.now, rng.Window),
} }
if u := web.Uptime(byRegion[r]); u >= 0 { if u := web.Uptime(byRegion[r]); u >= 0 {
h.Uptime = web.PercentPrecise(u) h.Uptime = web.PercentPrecise(u)
+2 -2
View File
@@ -472,7 +472,7 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
for _, a := range alertAssignments { for _, a := range alertAssignments {
alertGroupsByMonitor[a.MonitorID] = append(alertGroupsByMonitor[a.MonitorID], a.GroupID) alertGroupsByMonitor[a.MonitorID] = append(alertGroupsByMonitor[a.MonitorID], a.GroupID)
} }
regionRows, err := q.AllMonitorRegions(ctx) regionRows, err := q.AllMonitorRegions(ctx, p.Org.ID)
if err != nil { if err != nil {
return err return err
} }
@@ -480,7 +480,7 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
for _, r := range regionRows { for _, r := range regionRows {
regions[r.MonitorID] = append(regions[r.MonitorID], r.RegionID) regions[r.MonitorID] = append(regions[r.MonitorID], r.RegionID)
} }
monitors, err := q.ListMonitors(ctx) monitors, err := q.ListMonitors(ctx, p.Org.ID)
if err != nil { if err != nil {
return err return err
} }
+1 -2
View File
@@ -93,8 +93,7 @@ func (s *Server) recordPassive(ctx context.Context, region string, id, org uuid.
row.Error = ptr(truncateValid(msg, 500)) row.Error = ptr(truncateValid(msg, 500))
} }
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
_, err := q.InsertCheckResults(ctx, []store.InsertCheckResultsParams{row}) return insertResults(ctx, q, []store.InsertCheckResultsParams{row})
return err
}) })
if err != nil { if err != nil {
return err return err
+69
View File
@@ -0,0 +1,69 @@
package api_test
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
// TestLatestResultsKeepTheNewest checks that a result arriving late does
// not replace a newer one, and that a batch keeps its newest per region.
func TestLatestResultsKeepTheNewest(t *testing.T) {
e := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
owner.signup("o@"+uniq("lr")+".test", uniq("lr-"))
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://shop.test", "interval_seconds": 60, "regions": []string{region}})
id, org := uuid.MustParse(m["id"].(string)), uuid.MustParse(owner.orgID())
now := time.Now().Truncate(time.Millisecond)
upsert := func(rows ...map[string]any) {
t.Helper()
for _, r := range rows {
r["monitor_id"], r["org_id"], r["region"] = id, org, region
}
b, _ := json.Marshal(rows)
if err := e.asSystem(t, func(tx pgx.Tx) error { return store.New(tx).UpsertLatestResults(context.Background(), b) }); err != nil {
t.Fatal(err)
}
}
latest := func() (time.Time, bool) {
t.Helper()
var (
at time.Time
ok bool
)
if err := e.asSystem(t, func(tx pgx.Tx) error {
return tx.QueryRow(context.Background(), `SELECT time, ok FROM latest_results WHERE monitor_id = $1`, id).Scan(&at, &ok)
}); err != nil {
t.Fatal(err)
}
return at, ok
}
upsert(map[string]any{"time": now.Add(-time.Minute), "ok": true}, map[string]any{"time": now, "ok": false, "error": "down"})
if at, ok := latest(); !at.Equal(now) || ok {
t.Errorf("after a batch latest = %v ok=%t, want the newest (%v, failed)", at, ok, now)
}
upsert(map[string]any{"time": now.Add(-30 * time.Second), "ok": true})
if at, _ := latest(); !at.Equal(now) {
t.Errorf("a late result replaced the newest: %v", at)
}
upsert(map[string]any{"time": now.Add(time.Minute), "ok": true, "latency_ms": 12})
if at, ok := latest(); !at.Equal(now.Add(time.Minute)) || !ok {
t.Errorf("a newer result was not kept: %v ok=%t", at, ok)
}
_, body := owner.do("GET", "/api/v1/org/monitors", nil)
if got := body["monitors"].([]any)[0].(map[string]any)["latest"].([]any); len(got) != 1 {
t.Errorf("the API lists %d latest results, want 1", len(got))
}
if _, _, html := owner.page("/monitors/" + id.String()); !strings.Contains(html, "12 ms") {
t.Error("the monitor page does not show the latest result")
}
}
+1 -1
View File
@@ -234,7 +234,7 @@ func (s *Server) loadMaintenanceScope(ctx context.Context, p *principal) (mainte
return ms, err return ms, err
} }
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
rows, err := q.ListMonitors(ctx) rows, err := q.ListMonitors(ctx, p.Org.ID)
for _, m := range rows { for _, m := range rows {
ms.monitors[m.ID] = m ms.monitors[m.ID] = m
} }
+1 -1
View File
@@ -220,7 +220,7 @@ func (s *Server) listMonitors(c *gin.Context) {
for _, a := range assignments { for _, a := range assignments {
alertGroups[a.MonitorID] = append(alertGroups[a.MonitorID], a.GroupID) alertGroups[a.MonitorID] = append(alertGroups[a.MonitorID], a.GroupID)
} }
regions, err := q.AllMonitorRegions(ctx) regions, err := q.AllMonitorRegions(ctx, p.Org.ID)
if err != nil { if err != nil {
return err return err
} }
+7 -2
View File
@@ -55,8 +55,13 @@ func TestUncheckedMonitorsAndRegionsWithoutChecker(t *testing.T) {
if _, err := tx.Exec(ctx, `UPDATE monitors SET created_at = now() - interval '1 hour' WHERE id = $1`, id); err != nil { if _, err := tx.Exec(ctx, `UPDATE monitors SET created_at = now() - interval '1 hour' WHERE id = $1`, id); err != nil {
return err return err
} }
_, err := tx.Exec(ctx, `INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, $4, true, 10)`, if _, err := tx.Exec(ctx, `INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, $4, true, 10)`,
org, id, region, uuid.New()) org, id, region, uuid.New()); err != nil {
return err
}
// As the API keeps it when the result arrives.
_, err := tx.Exec(ctx, `INSERT INTO latest_results (time, org_id, monitor_id, region, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, true, 10)`,
org, id, region)
return err return err
}); err != nil { }); err != nil {
t.Fatal(err) t.Fatal(err)
+44
View File
@@ -0,0 +1,44 @@
package api
import (
"context"
"encoding/json"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
// latestRow is a result as UpsertLatestResults reads it.
type latestRow struct {
MonitorID uuid.UUID `json:"monitor_id"`
Region string `json:"region"`
OrgID uuid.UUID `json:"org_id"`
Time time.Time `json:"time"`
OK bool `json:"ok"`
LatencyMS *int32 `json:"latency_ms"`
StatusCode *int32 `json:"status_code"`
Error *string `json:"error"`
}
// insertResults stores results and keeps the newest per monitor and
// region in latest_results, which the console reads instead of a day of
// results.
func insertResults(ctx context.Context, q *store.Queries, rows []store.InsertCheckResultsParams) error {
if _, err := q.InsertCheckResults(ctx, rows); err != nil {
return err
}
latest := make([]latestRow, len(rows))
for i, r := range rows {
latest[i] = latestRow{
MonitorID: r.MonitorID, Region: r.Region, OrgID: r.OrgID, Time: r.Time, OK: r.Ok,
LatencyMS: r.LatencyMs, StatusCode: r.StatusCode, Error: r.Error,
}
}
b, err := json.Marshal(latest)
if err != nil {
return err
}
return q.UpsertLatestResults(ctx, b)
}
+8 -3
View File
@@ -84,10 +84,15 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
for i, m := range listed { for i, m := range listed {
ids[i] = m.MonitorID ids[i] = m.MonitorID
} }
if latest, err = q.LatestResults(ctx, page.OrgID); err != nil { rows, err := q.LatestResultsForMonitors(ctx, store.LatestResultsForMonitorsParams{OrgID: page.OrgID, Ids: ids})
if err != nil {
return err return err
} }
if open, err = q.OpenIncidents(ctx); err != nil { latest = make([]store.LatestResultsRow, len(rows))
for i, r := range rows {
latest[i] = store.LatestResultsRow(r)
}
if open, err = q.OpenIncidents(ctx, page.OrgID); err != nil {
return err return err
} }
if daily, err = q.DailyBucketsForMonitors(ctx, store.DailyBucketsForMonitorsParams{ if daily, err = q.DailyBucketsForMonitors(ctx, store.DailyBucketsForMonitorsParams{
@@ -97,7 +102,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
} }
if page.ShowComponentDetails { if page.ShowComponentDetails {
if hourly, err = q.HourlyBuckets(ctx, store.HourlyBucketsParams{ if hourly, err = q.HourlyBuckets(ctx, store.HourlyBucketsParams{
OrgID: page.OrgID, Bucket: now.UTC().Add(-24 * time.Hour), OrgID: page.OrgID, Bucket: now.UTC().Add(-24 * time.Hour), Ids: ids,
}); err != nil { }); err != nil {
return err return err
} }
@@ -0,0 +1,41 @@
-- +goose Up
-- The newest result per monitor and region, kept up to date as results
-- arrive. Finding it in check_results means reading a day of results of
-- every monitor, which made every console page slow for organizations
-- with many monitors.
CREATE TABLE latest_results (
monitor_id uuid NOT NULL,
region text NOT NULL,
org_id uuid NOT NULL,
time timestamptz NOT NULL,
ok boolean NOT NULL,
latency_ms integer,
status_code integer,
error text,
PRIMARY KEY (monitor_id, region),
FOREIGN KEY (monitor_id, org_id) REFERENCES monitors (id, org_id) ON DELETE CASCADE
);
CREATE INDEX latest_results_org_idx ON latest_results (org_id);
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
FROM check_results r
JOIN monitors m ON m.id = r.monitor_id AND m.org_id = r.org_id
WHERE r.time > now() - INTERVAL '1 day'
ORDER BY r.monitor_id, r.region, r.time DESC;
ALTER TABLE latest_results ENABLE ROW LEVEL SECURITY;
ALTER TABLE latest_results FORCE ROW LEVEL SECURITY;
CREATE POLICY latest_results_tenant ON latest_results FOR ALL
USING (app_scope_system() OR org_id = app_org_id())
WITH CHECK (app_scope_system() OR org_id = app_org_id());
-- Console queries name the organization so that these can be used; row
-- security alone does not let the planner use an index.
CREATE INDEX monitor_regions_org_idx ON monitor_regions (org_id);
CREATE INDEX incidents_open_org_idx ON incidents (org_id) WHERE resolved_at IS NULL;
-- +goose Down
DROP INDEX incidents_open_org_idx;
DROP INDEX monitor_regions_org_idx;
DROP TABLE latest_results;
+74 -74
View File
@@ -124,22 +124,65 @@ func (q *Queries) DailyBucketsForMonitors(ctx context.Context, arg DailyBucketsF
return items, nil return items, nil
} }
const earliestDataDaily = `-- name: EarliestDataDaily :one
SELECT bucket::timestamptz AS first FROM check_results_1d WHERE org_id = $1 ORDER BY bucket LIMIT 1
`
// The day the organization's monitors first reported, if any did.
func (q *Queries) EarliestDataDaily(ctx context.Context, orgID uuid.UUID) (time.Time, error) {
row := q.db.QueryRow(ctx, earliestDataDaily, orgID)
var first time.Time
err := row.Scan(&first)
return first, err
}
const earliestDataRecent = `-- name: EarliestDataRecent :one
SELECT f.time FROM monitors m
CROSS JOIN LATERAL (
SELECT c.time FROM check_results c
WHERE c.org_id = $1 AND c.monitor_id = m.id AND c.time >= $2
ORDER BY c.time LIMIT 1
) f
WHERE m.org_id = $1
ORDER BY f.time LIMIT 1
`
type EarliestDataRecentParams struct {
OrgID uuid.UUID
Time time.Time
}
// When the organization's monitors first reported since $2, exactly: the
// first result of each monitor is found through its index, so the cost
// does not grow with the days of results.
func (q *Queries) EarliestDataRecent(ctx context.Context, arg EarliestDataRecentParams) (time.Time, error) {
row := q.db.QueryRow(ctx, earliestDataRecent, arg.OrgID, arg.Time)
var time time.Time
err := row.Scan(&time)
return time, err
}
const firstDataDaily = `-- name: FirstDataDaily :many const firstDataDaily = `-- name: FirstDataDaily :many
SELECT monitor_id, region, min(bucket)::timestamptz AS first SELECT monitor_id, region, min(bucket)::timestamptz AS first
FROM check_results_1d FROM check_results_1d
WHERE org_id = $1 WHERE org_id = $1 AND monitor_id = $2
GROUP BY 1, 2 GROUP BY 1, 2
` `
type FirstDataDailyParams struct {
OrgID uuid.UUID
MonitorID uuid.UUID
}
type FirstDataDailyRow struct { type FirstDataDailyRow struct {
MonitorID uuid.UUID MonitorID uuid.UUID
Region string Region string
First time.Time First time.Time
} }
// When each monitor and region first reported, to the day. // When each region of a monitor first reported, to the day.
func (q *Queries) FirstDataDaily(ctx context.Context, orgID uuid.UUID) ([]FirstDataDailyRow, error) { func (q *Queries) FirstDataDaily(ctx context.Context, arg FirstDataDailyParams) ([]FirstDataDailyRow, error) {
rows, err := q.db.Query(ctx, firstDataDaily, orgID) rows, err := q.db.Query(ctx, firstDataDaily, arg.OrgID, arg.MonitorID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -161,13 +204,14 @@ func (q *Queries) FirstDataDaily(ctx context.Context, orgID uuid.UUID) ([]FirstD
const firstDataRecent = `-- name: FirstDataRecent :many const firstDataRecent = `-- name: FirstDataRecent :many
SELECT monitor_id, region, min(time)::timestamptz AS first SELECT monitor_id, region, min(time)::timestamptz AS first
FROM check_results FROM check_results
WHERE org_id = $1 AND time >= $2 WHERE org_id = $1 AND monitor_id = $2 AND time >= $3
GROUP BY 1, 2 GROUP BY 1, 2
` `
type FirstDataRecentParams struct { type FirstDataRecentParams struct {
OrgID uuid.UUID OrgID uuid.UUID
Time time.Time MonitorID uuid.UUID
Time time.Time
} }
type FirstDataRecentRow struct { type FirstDataRecentRow struct {
@@ -176,10 +220,10 @@ type FirstDataRecentRow struct {
First time.Time First time.Time
} }
// When each monitor and region first reported since $2, exactly. Used for // When each region of a monitor first reported since $3, exactly. Used for
// data younger than the daily aggregate's resolution. // data younger than the daily aggregate's resolution.
func (q *Queries) FirstDataRecent(ctx context.Context, arg FirstDataRecentParams) ([]FirstDataRecentRow, error) { func (q *Queries) FirstDataRecent(ctx context.Context, arg FirstDataRecentParams) ([]FirstDataRecentRow, error) {
rows, err := q.db.Query(ctx, firstDataRecent, arg.OrgID, arg.Time) rows, err := q.db.Query(ctx, firstDataRecent, arg.OrgID, arg.MonitorID, arg.Time)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -203,6 +247,7 @@ SELECT monitor_id, bucket::timestamptz AS bucket, sum(total)::bigint AS total, s
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1h FROM check_results_1h
WHERE org_id = $1 AND bucket >= $2 WHERE org_id = $1 AND bucket >= $2
AND ($3::uuid[] IS NULL OR monitor_id = ANY ($3::uuid[]))
GROUP BY monitor_id, bucket GROUP BY monitor_id, bucket
ORDER BY monitor_id, bucket ORDER BY monitor_id, bucket
` `
@@ -210,6 +255,7 @@ ORDER BY monitor_id, bucket
type HourlyBucketsParams struct { type HourlyBucketsParams struct {
OrgID uuid.UUID OrgID uuid.UUID
Bucket interface{} Bucket interface{}
Ids []uuid.UUID
} }
type HourlyBucketsRow struct { type HourlyBucketsRow struct {
@@ -222,7 +268,7 @@ type HourlyBucketsRow struct {
// Per monitor and hour since $2, across all regions. // Per monitor and hour since $2, across all regions.
func (q *Queries) HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error) { func (q *Queries) HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error) {
rows, err := q.db.Query(ctx, hourlyBuckets, arg.OrgID, arg.Bucket) rows, err := q.db.Query(ctx, hourlyBuckets, arg.OrgID, arg.Bucket, arg.Ids)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -259,52 +305,6 @@ type InsertCheckResultsParams struct {
Error *string Error *string
} }
const latestResults = `-- name: LatestResults :many
SELECT DISTINCT ON (monitor_id, region) monitor_id, region, time, ok, latency_ms, status_code, error
FROM check_results
WHERE org_id = $1 AND time > now() - interval '1 day'
ORDER BY monitor_id, region, time DESC
`
type LatestResultsRow struct {
MonitorID uuid.UUID
Region string
Time time.Time
Ok bool
LatencyMs *int32
StatusCode *int32
Error *string
}
// Newest result per monitor and region in the org.
func (q *Queries) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) {
rows, err := q.db.Query(ctx, latestResults, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LatestResultsRow{}
for rows.Next() {
var i LatestResultsRow
if err := rows.Scan(
&i.MonitorID,
&i.Region,
&i.Time,
&i.Ok,
&i.LatencyMs,
&i.StatusCode,
&i.Error,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const latestResultsForMonitor = `-- name: LatestResultsForMonitor :many const latestResultsForMonitor = `-- name: LatestResultsForMonitor :many
SELECT DISTINCT ON (region) region, ok, error SELECT DISTINCT ON (region) region, ok, error
FROM check_results FROM check_results
@@ -425,16 +425,16 @@ SELECT monitor_id, time_bucket($2::text::interval, time)::timestamptz AS bucket,
coalesce(avg(latency_ms), 0)::real AS avg_latency_ms coalesce(avg(latency_ms), 0)::real AS avg_latency_ms
FROM check_results FROM check_results
WHERE org_id = $1 AND time >= $3 WHERE org_id = $1 AND time >= $3
AND ($4::uuid IS NULL OR monitor_id = $4) AND monitor_id = ANY ($4::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2 ORDER BY 1, 2
` `
type RangeBucketsParams struct { type RangeBucketsParams struct {
OrgID uuid.UUID OrgID uuid.UUID
Width string Width string
Since time.Time Since time.Time
MonitorID *uuid.UUID Ids []uuid.UUID
} }
type RangeBucketsRow struct { type RangeBucketsRow struct {
@@ -451,7 +451,7 @@ func (q *Queries) RangeBuckets(ctx context.Context, arg RangeBucketsParams) ([]R
arg.OrgID, arg.OrgID,
arg.Width, arg.Width,
arg.Since, arg.Since,
arg.MonitorID, arg.Ids,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -483,16 +483,16 @@ SELECT monitor_id, time_bucket($2::text::interval, bucket)::timestamptz AS bucke
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1d FROM check_results_1d
WHERE org_id = $1 AND bucket >= $3 WHERE org_id = $1 AND bucket >= $3
AND ($4::uuid IS NULL OR monitor_id = $4) AND monitor_id = ANY ($4::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2 ORDER BY 1, 2
` `
type RangeBucketsDailyParams struct { type RangeBucketsDailyParams struct {
OrgID uuid.UUID OrgID uuid.UUID
Width string Width string
Since interface{} Since interface{}
MonitorID *uuid.UUID Ids []uuid.UUID
} }
type RangeBucketsDailyRow struct { type RangeBucketsDailyRow struct {
@@ -509,7 +509,7 @@ func (q *Queries) RangeBucketsDaily(ctx context.Context, arg RangeBucketsDailyPa
arg.OrgID, arg.OrgID,
arg.Width, arg.Width,
arg.Since, arg.Since,
arg.MonitorID, arg.Ids,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -541,16 +541,16 @@ SELECT monitor_id, time_bucket($2::text::interval, bucket)::timestamptz AS bucke
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1h FROM check_results_1h
WHERE org_id = $1 AND bucket >= $3 WHERE org_id = $1 AND bucket >= $3
AND ($4::uuid IS NULL OR monitor_id = $4) AND monitor_id = ANY ($4::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2 ORDER BY 1, 2
` `
type RangeBucketsHourlyParams struct { type RangeBucketsHourlyParams struct {
OrgID uuid.UUID OrgID uuid.UUID
Width string Width string
Since interface{} Since interface{}
MonitorID *uuid.UUID Ids []uuid.UUID
} }
type RangeBucketsHourlyRow struct { type RangeBucketsHourlyRow struct {
@@ -567,7 +567,7 @@ func (q *Queries) RangeBucketsHourly(ctx context.Context, arg RangeBucketsHourly
arg.OrgID, arg.OrgID,
arg.Width, arg.Width,
arg.Since, arg.Since,
arg.MonitorID, arg.Ids,
) )
if err != nil { if err != nil {
return nil, err return nil, err
+12 -7
View File
@@ -313,18 +313,23 @@ func (q *Queries) IncidentsForMonitors(ctx context.Context, arg IncidentsForMoni
const incidentsSince = `-- name: IncidentsSince :many const incidentsSince = `-- name: IncidentsSince :many
SELECT monitor_id, started_at, resolved_at FROM incidents SELECT monitor_id, started_at, resolved_at FROM incidents
WHERE resolved_at IS NULL OR resolved_at > $1 WHERE org_id = $1 AND (resolved_at IS NULL OR resolved_at > $2)
` `
type IncidentsSinceParams struct {
OrgID uuid.UUID
ResolvedAt *time.Time
}
type IncidentsSinceRow struct { type IncidentsSinceRow struct {
MonitorID uuid.UUID MonitorID uuid.UUID
StartedAt time.Time StartedAt time.Time
ResolvedAt *time.Time ResolvedAt *time.Time
} }
// Incidents overlapping the time since $1, for SLA calculation. // Incidents overlapping the time since $2, for SLA calculation.
func (q *Queries) IncidentsSince(ctx context.Context, resolvedAt *time.Time) ([]IncidentsSinceRow, error) { func (q *Queries) IncidentsSince(ctx context.Context, arg IncidentsSinceParams) ([]IncidentsSinceRow, error) {
rows, err := q.db.Query(ctx, incidentsSince, resolvedAt) rows, err := q.db.Query(ctx, incidentsSince, arg.OrgID, arg.ResolvedAt)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -672,11 +677,11 @@ func (q *Queries) OpenIncident(ctx context.Context, arg OpenIncidentParams) (Inc
} }
const openIncidents = `-- name: OpenIncidents :many const openIncidents = `-- name: OpenIncidents :many
SELECT id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id FROM incidents WHERE resolved_at IS NULL SELECT id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id FROM incidents WHERE org_id = $1 AND resolved_at IS NULL
` `
func (q *Queries) OpenIncidents(ctx context.Context) ([]Incident, error) { func (q *Queries) OpenIncidents(ctx context.Context, orgID uuid.UUID) ([]Incident, error) {
rows, err := q.db.Query(ctx, openIncidents) rows, err := q.db.Query(ctx, openIncidents, orgID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+130
View File
@@ -0,0 +1,130 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: latest_results.sql
package store
import (
"context"
"time"
"github.com/google/uuid"
)
const latestResults = `-- name: LatestResults :many
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
FROM latest_results
WHERE org_id = $1 AND time > now() - interval '1 day'
`
type LatestResultsRow struct {
MonitorID uuid.UUID
Region string
Time time.Time
Ok bool
LatencyMs *int32
StatusCode *int32
Error *string
}
// Newest result per monitor and region in the org, of the last day.
func (q *Queries) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) {
rows, err := q.db.Query(ctx, latestResults, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LatestResultsRow{}
for rows.Next() {
var i LatestResultsRow
if err := rows.Scan(
&i.MonitorID,
&i.Region,
&i.Time,
&i.Ok,
&i.LatencyMs,
&i.StatusCode,
&i.Error,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const latestResultsForMonitors = `-- name: LatestResultsForMonitors :many
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
FROM latest_results
WHERE org_id = $1 AND monitor_id = ANY ($2::uuid[]) AND time > now() - interval '1 day'
`
type LatestResultsForMonitorsParams struct {
OrgID uuid.UUID
Ids []uuid.UUID
}
type LatestResultsForMonitorsRow struct {
MonitorID uuid.UUID
Region string
Time time.Time
Ok bool
LatencyMs *int32
StatusCode *int32
Error *string
}
// LatestResults limited to the monitors ids.
func (q *Queries) LatestResultsForMonitors(ctx context.Context, arg LatestResultsForMonitorsParams) ([]LatestResultsForMonitorsRow, error) {
rows, err := q.db.Query(ctx, latestResultsForMonitors, arg.OrgID, arg.Ids)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LatestResultsForMonitorsRow{}
for rows.Next() {
var i LatestResultsForMonitorsRow
if err := rows.Scan(
&i.MonitorID,
&i.Region,
&i.Time,
&i.Ok,
&i.LatencyMs,
&i.StatusCode,
&i.Error,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const upsertLatestResults = `-- name: UpsertLatestResults :exec
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
FROM jsonb_to_recordset($1::jsonb)
AS r(monitor_id uuid, region text, org_id uuid, time timestamptz, ok boolean, latency_ms integer, status_code integer, error text)
ORDER BY r.monitor_id, r.region, r.time DESC
ON CONFLICT (monitor_id, region) DO UPDATE
SET org_id = excluded.org_id, time = excluded.time, ok = excluded.ok, latency_ms = excluded.latency_ms,
status_code = excluded.status_code, error = excluded.error
WHERE latest_results.time <= excluded.time
`
// latest_results holds the newest check result per monitor and region
// (see migration 00055) and has row-level security.
// Keeps the newest of rows, a JSON array of results, per monitor and
// region; results arriving late do not replace newer ones.
func (q *Queries) UpsertLatestResults(ctx context.Context, rows []byte) error {
_, err := q.db.Exec(ctx, upsertLatestResults, rows)
return err
}
+11
View File
@@ -197,6 +197,17 @@ type Invitation struct {
CreatedAt time.Time CreatedAt time.Time
} }
type LatestResult struct {
MonitorID uuid.UUID
Region string
OrgID uuid.UUID
Time time.Time
Ok bool
LatencyMs *int32
StatusCode *int32
Error *string
}
type LegalAcceptance struct { type LegalAcceptance struct {
UserID uuid.UUID UserID uuid.UUID
Kind string Kind string
+7 -6
View File
@@ -27,7 +27,7 @@ func (q *Queries) AddMonitorRegion(ctx context.Context, arg AddMonitorRegionPara
} }
const allMonitorRegions = `-- name: AllMonitorRegions :many const allMonitorRegions = `-- name: AllMonitorRegions :many
SELECT monitor_id, region_id FROM monitor_regions SELECT monitor_id, region_id FROM monitor_regions WHERE org_id = $1
` `
type AllMonitorRegionsRow struct { type AllMonitorRegionsRow struct {
@@ -35,8 +35,8 @@ type AllMonitorRegionsRow struct {
RegionID uuid.UUID RegionID uuid.UUID
} }
func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) { func (q *Queries) AllMonitorRegions(ctx context.Context, orgID uuid.UUID) ([]AllMonitorRegionsRow, error) {
rows, err := q.db.Query(ctx, allMonitorRegions) rows, err := q.db.Query(ctx, allMonitorRegions, orgID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -192,11 +192,12 @@ func (q *Queries) ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEna
} }
const listMonitors = `-- name: ListMonitors :many const listMonitors = `-- name: ListMonitors :many
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position FROM monitors ORDER BY name SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position FROM monitors WHERE org_id = $1 ORDER BY name
` `
func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) { // The org filter, though row security implies it, lets the index be used.
rows, err := q.db.Query(ctx, listMonitors) func (q *Queries) ListMonitors(ctx context.Context, orgID uuid.UUID) ([]Monitor, error) {
rows, err := q.db.Query(ctx, listMonitors, orgID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+23 -9
View File
@@ -39,7 +39,7 @@ type Querier interface {
// System scope: the receiver a webhook token belongs to. // System scope: the receiver a webhook token belongs to.
AlertmanagerReceiverByHash(ctx context.Context, tokenHash []byte) (AlertmanagerReceiverByHashRow, error) AlertmanagerReceiverByHash(ctx context.Context, tokenHash []byte) (AlertmanagerReceiverByHashRow, error)
AllMonitorAlertGroups(ctx context.Context) ([]MonitorAlertGroup, error) AllMonitorAlertGroups(ctx context.Context) ([]MonitorAlertGroup, error)
AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) AllMonitorRegions(ctx context.Context, orgID uuid.UUID) ([]AllMonitorRegionsRow, error)
AnyUserExists(ctx context.Context) (bool, error) AnyUserExists(ctx context.Context) (bool, error)
// How much one instance checked for the organization in the last hour. // How much one instance checked for the organization in the last hour.
CheckerStats(ctx context.Context, arg CheckerStatsParams) (CheckerStatsRow, error) CheckerStats(ctx context.Context, arg CheckerStatsParams) (CheckerStatsRow, error)
@@ -124,6 +124,12 @@ type Querier interface {
// for two days, after which only the verify button tries again. A verified // for two days, after which only the verify button tries again. A verified
// one is checked daily, hourly once its record went missing. // one is checked daily, hourly once its record went missing.
DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error) DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error)
// The day the organization's monitors first reported, if any did.
EarliestDataDaily(ctx context.Context, orgID uuid.UUID) (time.Time, error)
// When the organization's monitors first reported since $2, exactly: the
// first result of each monitor is found through its index, so the cost
// does not grow with the days of results.
EarliestDataRecent(ctx context.Context, arg EarliestDataRecentParams) (time.Time, error)
EmailKeyTaken(ctx context.Context, emailKey *string) (bool, error) EmailKeyTaken(ctx context.Context, emailKey *string) (bool, error)
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error
@@ -139,9 +145,9 @@ type Querier interface {
// FiringAlerts newest first, a page from a keyset cursor (see paging.go) // FiringAlerts newest first, a page from a keyset cursor (see paging.go)
// whose string key is the fingerprint. // whose string key is the fingerprint.
FiringAlertsPage(ctx context.Context, arg FiringAlertsPageParams) ([]FiringAlertsPageRow, error) FiringAlertsPage(ctx context.Context, arg FiringAlertsPageParams) ([]FiringAlertsPageRow, error)
// When each monitor and region first reported, to the day. // When each region of a monitor first reported, to the day.
FirstDataDaily(ctx context.Context, orgID uuid.UUID) ([]FirstDataDailyRow, error) FirstDataDaily(ctx context.Context, arg FirstDataDailyParams) ([]FirstDataDailyRow, error)
// When each monitor and region first reported since $2, exactly. Used for // When each region of a monitor first reported since $3, exactly. Used for
// data younger than the daily aggregate's resolution. // data younger than the daily aggregate's resolution.
FirstDataRecent(ctx context.Context, arg FirstDataRecentParams) ([]FirstDataRecentRow, error) FirstDataRecent(ctx context.Context, arg FirstDataRecentParams) ([]FirstDataRecentRow, error)
// Keeps organization and platform entries readable as "deleted user" but // Keeps organization and platform entries readable as "deleted user" but
@@ -184,8 +190,8 @@ type Querier interface {
// Per monitor and hour since $2, across all regions. // Per monitor and hour since $2, across all regions.
HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error) HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error)
IncidentsForMonitors(ctx context.Context, arg IncidentsForMonitorsParams) ([]Incident, error) IncidentsForMonitors(ctx context.Context, arg IncidentsForMonitorsParams) ([]Incident, error)
// Incidents overlapping the time since $1, for SLA calculation. // Incidents overlapping the time since $2, for SLA calculation.
IncidentsSince(ctx context.Context, resolvedAt *time.Time) ([]IncidentsSinceRow, error) IncidentsSince(ctx context.Context, arg IncidentsSinceParams) ([]IncidentsSinceRow, error)
InsertAuditEvent(ctx context.Context, arg InsertAuditEventParams) error InsertAuditEvent(ctx context.Context, arg InsertAuditEventParams) error
// check_results and its aggregates have no row-level security (see // check_results and its aggregates have no row-level security (see
// migration 00013). Every query here must filter by org_id. // migration 00013). Every query here must filter by org_id.
@@ -196,9 +202,11 @@ type Querier interface {
IsMember(ctx context.Context, arg IsMemberParams) (bool, error) IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error)
LatestResultForMonitor(ctx context.Context, arg LatestResultForMonitorParams) (LatestResultForMonitorRow, error) LatestResultForMonitor(ctx context.Context, arg LatestResultForMonitorParams) (LatestResultForMonitorRow, error)
// Newest result per monitor and region in the org. // Newest result per monitor and region in the org, of the last day.
LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error)
LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error) LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error)
// LatestResults limited to the monitors ids.
LatestResultsForMonitors(ctx context.Context, arg LatestResultsForMonitorsParams) ([]LatestResultsForMonitorsRow, error)
LegalAcceptances(ctx context.Context, userID uuid.UUID) ([]LegalAcceptancesRow, error) LegalAcceptances(ctx context.Context, userID uuid.UUID) ([]LegalAcceptancesRow, error)
// The organization's documents and the platform's, organization first. // The organization's documents and the platform's, organization first.
LegalDocuments(ctx context.Context, orgID *uuid.UUID) ([]LegalDocument, error) LegalDocuments(ctx context.Context, orgID *uuid.UUID) ([]LegalDocument, error)
@@ -229,7 +237,8 @@ type Querier interface {
// Latest start first, a page from a keyset cursor (see paging.go). // Latest start first, a page from a keyset cursor (see paging.go).
ListMaintenancePage(ctx context.Context, arg ListMaintenancePageParams) ([]MaintenanceWindow, error) ListMaintenancePage(ctx context.Context, arg ListMaintenancePageParams) ([]MaintenanceWindow, error)
ListMaintenanceTargets(ctx context.Context) ([]MaintenanceTarget, error) ListMaintenanceTargets(ctx context.Context) ([]MaintenanceTarget, error)
ListMonitors(ctx context.Context) ([]Monitor, error) // The org filter, though row security implies it, lets the index be used.
ListMonitors(ctx context.Context, orgID uuid.UUID) ([]Monitor, error)
// By name, a page from a keyset cursor (see paging.go). // By name, a page from a keyset cursor (see paging.go).
ListMonitorsPage(ctx context.Context, arg ListMonitorsPageParams) ([]Monitor, error) ListMonitorsPage(ctx context.Context, arg ListMonitorsPageParams) ([]Monitor, error)
ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error)
@@ -291,7 +300,7 @@ type Querier interface {
// System scope. // System scope.
NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]NotificationDetailsRow, error) NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]NotificationDetailsRow, error)
OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error) OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error)
OpenIncidents(ctx context.Context) ([]Incident, error) OpenIncidents(ctx context.Context, orgID uuid.UUID) ([]Incident, error)
OrgAssignmentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgAssignmentsExportRow, error) OrgAssignmentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgAssignmentsExportRow, error)
OrgAuditExport(ctx context.Context, orgID uuid.UUID) ([]OrgAuditExportRow, error) OrgAuditExport(ctx context.Context, orgID uuid.UUID) ([]OrgAuditExportRow, error)
OrgDailyStats(ctx context.Context, orgID uuid.UUID) ([]OrgDailyStatsRow, error) OrgDailyStats(ctx context.Context, orgID uuid.UUID) ([]OrgDailyStatsRow, error)
@@ -417,6 +426,11 @@ type Querier interface {
UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error) UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error)
UpdateStatusPageGroup(ctx context.Context, arg UpdateStatusPageGroupParams) (StatusPageGroup, error) UpdateStatusPageGroup(ctx context.Context, arg UpdateStatusPageGroupParams) (StatusPageGroup, error)
UpsertAlertmanagerAlert(ctx context.Context, arg UpsertAlertmanagerAlertParams) error UpsertAlertmanagerAlert(ctx context.Context, arg UpsertAlertmanagerAlertParams) error
// latest_results holds the newest check result per monitor and region
// (see migration 00055) and has row-level security.
// Keeps the newest of rows, a JSON array of results, per monitor and
// region; results arriving late do not replace newer ones.
UpsertLatestResults(ctx context.Context, rows []byte) error
// A new version starts when the document is created or when the edit asks // A new version starts when the document is created or when the edit asks
// everyone to accept it again. // everyone to accept it again.
UpsertLegalDocument(ctx context.Context, arg UpsertLegalDocumentParams) error UpsertLegalDocument(ctx context.Context, arg UpsertLegalDocumentParams) error
+25 -14
View File
@@ -5,13 +5,6 @@
INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms, status_code, error) INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms, status_code, error)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9); VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
-- name: LatestResults :many
-- Newest result per monitor and region in the org.
SELECT DISTINCT ON (monitor_id, region) monitor_id, region, time, ok, latency_ms, status_code, error
FROM check_results
WHERE org_id = $1 AND time > now() - interval '1 day'
ORDER BY monitor_id, region, time DESC;
-- name: ListResults :many -- name: ListResults :many
-- A monitor's results newest first, a page from a keyset cursor (see -- A monitor's results newest first, a page from a keyset cursor (see
-- paging.go) whose string key is region and checker. -- paging.go) whose string key is region and checker.
@@ -49,6 +42,7 @@ SELECT monitor_id, bucket::timestamptz AS bucket, sum(total)::bigint AS total, s
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1h FROM check_results_1h
WHERE org_id = $1 AND bucket >= $2 WHERE org_id = $1 AND bucket >= $2
AND (sqlc.narg(ids)::uuid[] IS NULL OR monitor_id = ANY (sqlc.narg(ids)::uuid[]))
GROUP BY monitor_id, bucket GROUP BY monitor_id, bucket
ORDER BY monitor_id, bucket; ORDER BY monitor_id, bucket;
@@ -73,7 +67,7 @@ SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, time)::timestamp
coalesce(avg(latency_ms), 0)::real AS avg_latency_ms coalesce(avg(latency_ms), 0)::real AS avg_latency_ms
FROM check_results FROM check_results
WHERE org_id = $1 AND time >= sqlc.arg(since) WHERE org_id = $1 AND time >= sqlc.arg(since)
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id)) AND monitor_id = ANY (sqlc.arg(ids)::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2; ORDER BY 1, 2;
@@ -84,7 +78,7 @@ SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, bucket)::timesta
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1h FROM check_results_1h
WHERE org_id = $1 AND bucket >= sqlc.arg(since) WHERE org_id = $1 AND bucket >= sqlc.arg(since)
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id)) AND monitor_id = ANY (sqlc.arg(ids)::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2; ORDER BY 1, 2;
@@ -95,7 +89,7 @@ SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, bucket)::timesta
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1d FROM check_results_1d
WHERE org_id = $1 AND bucket >= sqlc.arg(since) WHERE org_id = $1 AND bucket >= sqlc.arg(since)
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id)) AND monitor_id = ANY (sqlc.arg(ids)::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2; ORDER BY 1, 2;
@@ -125,18 +119,35 @@ GROUP BY 1, 2
ORDER BY 1, 2; ORDER BY 1, 2;
-- name: FirstDataDaily :many -- name: FirstDataDaily :many
-- When each monitor and region first reported, to the day. -- When each region of a monitor first reported, to the day.
SELECT monitor_id, region, min(bucket)::timestamptz AS first SELECT monitor_id, region, min(bucket)::timestamptz AS first
FROM check_results_1d FROM check_results_1d
WHERE org_id = $1 WHERE org_id = $1 AND monitor_id = $2
GROUP BY 1, 2; GROUP BY 1, 2;
-- name: EarliestDataDaily :one
-- The day the organization's monitors first reported, if any did.
SELECT bucket::timestamptz AS first FROM check_results_1d WHERE org_id = $1 ORDER BY bucket LIMIT 1;
-- name: EarliestDataRecent :one
-- When the organization's monitors first reported since $2, exactly: the
-- first result of each monitor is found through its index, so the cost
-- does not grow with the days of results.
SELECT f.time FROM monitors m
CROSS JOIN LATERAL (
SELECT c.time FROM check_results c
WHERE c.org_id = $1 AND c.monitor_id = m.id AND c.time >= $2
ORDER BY c.time LIMIT 1
) f
WHERE m.org_id = $1
ORDER BY f.time LIMIT 1;
-- name: FirstDataRecent :many -- name: FirstDataRecent :many
-- When each monitor and region first reported since $2, exactly. Used for -- When each region of a monitor first reported since $3, exactly. Used for
-- data younger than the daily aggregate's resolution. -- data younger than the daily aggregate's resolution.
SELECT monitor_id, region, min(time)::timestamptz AS first SELECT monitor_id, region, min(time)::timestamptz AS first
FROM check_results FROM check_results
WHERE org_id = $1 AND time >= $2 WHERE org_id = $1 AND monitor_id = $2 AND time >= $3
GROUP BY 1, 2; GROUP BY 1, 2;
-- name: ResultsByChecker :many -- name: ResultsByChecker :many
+3 -3
View File
@@ -84,7 +84,7 @@ SELECT * FROM notification_channels ORDER BY name;
DELETE FROM notification_channels WHERE id = $1; DELETE FROM notification_channels WHERE id = $1;
-- name: OpenIncidents :many -- name: OpenIncidents :many
SELECT * FROM incidents WHERE resolved_at IS NULL; SELECT * FROM incidents WHERE org_id = $1 AND resolved_at IS NULL;
-- name: IncidentsForMonitors :many -- name: IncidentsForMonitors :many
SELECT * FROM incidents SELECT * FROM incidents
@@ -93,9 +93,9 @@ ORDER BY started_at DESC
LIMIT 50; LIMIT 50;
-- name: IncidentsSince :many -- name: IncidentsSince :many
-- Incidents overlapping the time since $1, for SLA calculation. -- Incidents overlapping the time since $2, for SLA calculation.
SELECT monitor_id, started_at, resolved_at FROM incidents SELECT monitor_id, started_at, resolved_at FROM incidents
WHERE resolved_at IS NULL OR resolved_at > $1; WHERE org_id = $1 AND (resolved_at IS NULL OR resolved_at > $2);
-- name: GetIncident :one -- name: GetIncident :one
SELECT i.*, m.name AS monitor_name, m.group_id AS monitor_group_id SELECT i.*, m.name AS monitor_name, m.group_id AS monitor_group_id
+27
View File
@@ -0,0 +1,27 @@
-- latest_results holds the newest check result per monitor and region
-- (see migration 00055) and has row-level security.
-- name: UpsertLatestResults :exec
-- Keeps the newest of rows, a JSON array of results, per monitor and
-- region; results arriving late do not replace newer ones.
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
FROM jsonb_to_recordset(sqlc.arg(rows)::jsonb)
AS r(monitor_id uuid, region text, org_id uuid, time timestamptz, ok boolean, latency_ms integer, status_code integer, error text)
ORDER BY r.monitor_id, r.region, r.time DESC
ON CONFLICT (monitor_id, region) DO UPDATE
SET org_id = excluded.org_id, time = excluded.time, ok = excluded.ok, latency_ms = excluded.latency_ms,
status_code = excluded.status_code, error = excluded.error
WHERE latest_results.time <= excluded.time;
-- name: LatestResults :many
-- Newest result per monitor and region in the org, of the last day.
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
FROM latest_results
WHERE org_id = $1 AND time > now() - interval '1 day';
-- name: LatestResultsForMonitors :many
-- LatestResults limited to the monitors ids.
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
FROM latest_results
WHERE org_id = $1 AND monitor_id = ANY (sqlc.arg(ids)::uuid[]) AND time > now() - interval '1 day';
+3 -2
View File
@@ -16,13 +16,14 @@ DELETE FROM monitors WHERE id = $1;
SELECT * FROM monitors WHERE id = $1; SELECT * FROM monitors WHERE id = $1;
-- name: ListMonitors :many -- name: ListMonitors :many
SELECT * FROM monitors ORDER BY name; -- The org filter, though row security implies it, lets the index be used.
SELECT * FROM monitors WHERE org_id = $1 ORDER BY name;
-- name: MonitorRegions :many -- name: MonitorRegions :many
SELECT region_id FROM monitor_regions WHERE monitor_id = $1 ORDER BY region_id; SELECT region_id FROM monitor_regions WHERE monitor_id = $1 ORDER BY region_id;
-- name: AllMonitorRegions :many -- name: AllMonitorRegions :many
SELECT monitor_id, region_id FROM monitor_regions; SELECT monitor_id, region_id FROM monitor_regions WHERE org_id = $1;
-- name: DeleteMonitorRegions :exec -- name: DeleteMonitorRegions :exec
DELETE FROM monitor_regions WHERE monitor_id = $1; DELETE FROM monitor_regions WHERE monitor_id = $1;