Merge pull request 'perf(console): faster dashboard for organizations with thousands of monitors' (#164) from perf/dashboard-large-orgs into main
This commit was merged in pull request #164.
This commit is contained in:
commit
383b63bc0e
8 files changed
+147
-120
No files matched your search
+70
-55
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
@@ -72,8 +73,10 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true}
|
||||
timer := newStepTimer()
|
||||
if p != nil && me.Policy == "" {
|
||||
data, err := s.loadMonitorData(c.Request.Context(), p, web.RangeByKey(c.Query("range")))
|
||||
timer.done("load")
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -84,21 +87,14 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
if !s.dashboardPage(c, &v, data) {
|
||||
return
|
||||
}
|
||||
timer.done("arrange")
|
||||
if err := s.dashboardBars(c.Request.Context(), p, &v, &data); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
timer.done("bars")
|
||||
v.Range = data.rng.Key
|
||||
var earliest time.Time
|
||||
if err := s.db.Tx(c.Request.Context(), p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
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, data.firstCreated, data.now)
|
||||
for _, m := range data.rows {
|
||||
v.Counts[m.Status]++
|
||||
if m.Unchecked {
|
||||
@@ -111,7 +107,11 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
}
|
||||
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
|
||||
}
|
||||
timer.done("rest")
|
||||
timer.header(c)
|
||||
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
|
||||
timer.done("render")
|
||||
timer.logIfSlow(c, s.log)
|
||||
}
|
||||
|
||||
// dashboardBars loads the bars of the monitors v shows, and only those.
|
||||
@@ -218,13 +218,28 @@ func (o monitorSort) key(m web.MonitorRow) cursor {
|
||||
}
|
||||
|
||||
func (o monitorSort) sort(ms []web.MonitorRow) {
|
||||
slices.SortFunc(ms, func(a, b web.MonitorRow) int {
|
||||
ka, kb := o.key(a), o.key(b)
|
||||
if c := strings.Compare(ka.S, kb.S); c != 0 {
|
||||
// Keys are worked out once per row, not per comparison, and the rows
|
||||
// moved once: with thousands of monitors sorting was a good part of
|
||||
// the dashboard's time.
|
||||
type keyed struct {
|
||||
key, id string
|
||||
i int
|
||||
}
|
||||
keys := make([]keyed, len(ms))
|
||||
for i, m := range ms {
|
||||
keys[i] = keyed{o.key(m).S, m.ID, i}
|
||||
}
|
||||
slices.SortFunc(keys, func(a, b keyed) int {
|
||||
if c := strings.Compare(a.key, b.key); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(a.ID, b.ID)
|
||||
return strings.Compare(a.id, b.id)
|
||||
})
|
||||
sorted := make([]web.MonitorRow, len(ms))
|
||||
for i, k := range keys {
|
||||
sorted[i] = ms[k.i]
|
||||
}
|
||||
copy(ms, sorted)
|
||||
}
|
||||
|
||||
// dashboardStatuses are the statuses the dashboard counts, in order.
|
||||
@@ -379,6 +394,11 @@ type monitorData struct {
|
||||
regionOf map[uuid.UUID]store.Region
|
||||
rng web.TimeRange
|
||||
now time.Time
|
||||
// firstCreated is when the oldest monitor was created: the monitor
|
||||
// list offers no ranges reaching far before it. (Finding the first
|
||||
// result instead read results of every monitor, slow for large
|
||||
// organizations.)
|
||||
firstCreated time.Time
|
||||
// first is when the monitor of a detail page first reported, from
|
||||
// any region; firstRegion the same per region.
|
||||
first time.Time
|
||||
@@ -423,25 +443,6 @@ func loadFirstData(ctx context.Context, q *store.Queries, org, monitor uuid.UUID
|
||||
return first, perRegion, nil
|
||||
}
|
||||
|
||||
// earliestData finds when any monitor of org first reported, for the
|
||||
// ranges the monitor list offers: to the day if that was over two days
|
||||
// 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{}
|
||||
@@ -498,39 +499,50 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
spans []store.IncidentsSinceRow
|
||||
)
|
||||
var groups []store.MonitorGroup
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
// The queries run in parallel: for large organizations each takes a
|
||||
// while, mostly to move its rows.
|
||||
g, gctx := errgroup.WithContext(ctx)
|
||||
tx := func(f func(q *store.Queries) error) {
|
||||
g.Go(func() error { return s.db.Tx(gctx, p.scope(), f) })
|
||||
}
|
||||
tx(func(q *store.Queries) error {
|
||||
var err error
|
||||
if groups, err = q.ListGroups(ctx); err != nil {
|
||||
if groups, err = q.ListGroups(gctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if assigned, err = q.AllMonitorRegions(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if regions, err = q.ListVisibleRegions(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if open, err = q.OpenIncidents(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
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.statuses, err = loadCustomStatuses(ctx, q); err != nil {
|
||||
if monitors, err = q.ListMonitors(gctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
ids := make([]uuid.UUID, len(monitors))
|
||||
for i, m := range monitors {
|
||||
ids[i] = m.ID
|
||||
}
|
||||
d.maint, err = maintenanceFor(ctx, q, ids)
|
||||
d.maint, err = maintenanceFor(gctx, q, ids)
|
||||
return err
|
||||
})
|
||||
tx(func(q *store.Queries) (err error) {
|
||||
assigned, err = q.AllMonitorRegions(gctx, p.Org.ID)
|
||||
return err
|
||||
})
|
||||
tx(func(q *store.Queries) (err error) {
|
||||
latest, err = q.LatestResults(gctx, p.Org.ID)
|
||||
return err
|
||||
})
|
||||
tx(func(q *store.Queries) error {
|
||||
var err error
|
||||
if regions, err = q.ListVisibleRegions(gctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if open, err = q.OpenIncidents(gctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if spans, err = q.IncidentsSince(gctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
|
||||
return err
|
||||
}
|
||||
d.statuses, err = loadCustomStatuses(gctx, q)
|
||||
return err
|
||||
})
|
||||
err := g.Wait()
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
@@ -553,6 +565,9 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
if m.Enabled {
|
||||
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
|
||||
}
|
||||
if d.firstCreated.IsZero() || m.CreatedAt.Before(d.firstCreated) {
|
||||
d.firstCreated = m.CreatedAt
|
||||
}
|
||||
}
|
||||
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
||||
d.usedRegions = slices.Compact(d.usedRegions)
|
||||
|
||||
@@ -224,7 +224,11 @@ func (s *Server) listMonitors(c *gin.Context) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
latest, err := q.LatestResults(ctx, p.Org.ID)
|
||||
ids := make([]uuid.UUID, len(monitors))
|
||||
for i, m := range monitors {
|
||||
ids[i] = m.ID
|
||||
}
|
||||
latest, err := q.LatestResultsForMonitors(ctx, store.LatestResultsForMonitorsParams{OrgID: p.Org.ID, Ids: ids})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func TestTimeRangesAndSLA(t *testing.T) {
|
||||
@@ -53,7 +54,7 @@ func TestTimeRangesAndSLA(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 48, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52}
|
||||
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 24, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52}
|
||||
for key, n := range bars {
|
||||
st, _, html := owner.page("/?range=" + key)
|
||||
if st != http.StatusOK {
|
||||
@@ -99,9 +100,16 @@ func TestRangeAvailabilityAndRegions(t *testing.T) {
|
||||
id := uuid.MustParse(body["id"].(string))
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
|
||||
// Two hours of results: eu always fine, us always failing.
|
||||
// Two hours of results: eu always fine, us always failing. (The
|
||||
// monitor is as old as its results.)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE monitors SET created_at = $1 WHERE id = $2`, now.Add(-121*time.Minute), id)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checker := uuid.New()
|
||||
for m := 0; m <= 120; m += 5 {
|
||||
at := now.Add(-time.Duration(m) * time.Minute)
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// slowPage is when a console page logs how long its steps took.
|
||||
const slowPage = time.Second
|
||||
|
||||
// stepTimer measures the steps of a request. It reports them to the
|
||||
// browser in a Server-Timing header and, when the request was slow, in
|
||||
// the log.
|
||||
type stepTimer struct {
|
||||
start, last time.Time
|
||||
steps []step
|
||||
}
|
||||
|
||||
type step struct {
|
||||
name string
|
||||
d time.Duration
|
||||
}
|
||||
|
||||
func newStepTimer() *stepTimer {
|
||||
now := time.Now()
|
||||
return &stepTimer{start: now, last: now}
|
||||
}
|
||||
|
||||
// done ends the step name.
|
||||
func (t *stepTimer) done(name string) {
|
||||
now := time.Now()
|
||||
t.steps = append(t.steps, step{name, now.Sub(t.last)})
|
||||
t.last = now
|
||||
}
|
||||
|
||||
// header sets the Server-Timing header of the steps so far; call it
|
||||
// before the body is written.
|
||||
func (t *stepTimer) header(c *gin.Context) {
|
||||
parts := make([]string, len(t.steps))
|
||||
for i, s := range t.steps {
|
||||
parts[i] = fmt.Sprintf("%s;dur=%.1f", s.name, float64(s.d.Microseconds())/1000)
|
||||
}
|
||||
c.Header("Server-Timing", strings.Join(parts, ", "))
|
||||
}
|
||||
|
||||
// logIfSlow logs the steps when the request took slowPage or longer.
|
||||
func (t *stepTimer) logIfSlow(c *gin.Context, log *slog.Logger) {
|
||||
total := time.Since(t.start)
|
||||
if total < slowPage {
|
||||
return
|
||||
}
|
||||
attrs := []any{"path", c.Request.URL.Path, "total_ms", total.Milliseconds()}
|
||||
for _, s := range t.steps {
|
||||
attrs = append(attrs, s.name+"_ms", s.d.Milliseconds())
|
||||
}
|
||||
log.WarnContext(c.Request.Context(), "slow console page", attrs...)
|
||||
}
|
||||
@@ -124,44 +124,6 @@ func (q *Queries) DailyBucketsForMonitors(ctx context.Context, arg DailyBucketsF
|
||||
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
|
||||
SELECT monitor_id, region, min(bucket)::timestamptz AS first
|
||||
FROM check_results_1d
|
||||
|
||||
@@ -133,12 +133,6 @@ type Querier interface {
|
||||
// for two days, after which only the verify button tries again. A verified
|
||||
// one is checked daily, hourly once its record went missing.
|
||||
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)
|
||||
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
|
||||
EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error
|
||||
|
||||
@@ -125,23 +125,6 @@ FROM check_results_1d
|
||||
WHERE org_id = $1 AND monitor_id = $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
|
||||
-- When each region of a monitor first reported since $3, exactly. Used for
|
||||
-- data younger than the daily aggregate's resolution.
|
||||
|
||||
@@ -33,7 +33,7 @@ var Ranges = []TimeRange{
|
||||
{Key: "1h", Window: time.Hour, Bucket: time.Minute, Layout: "15:04"},
|
||||
{Key: "3h", Window: 3 * time.Hour, Bucket: 5 * time.Minute, Layout: "15:04"},
|
||||
{Key: "12h", Window: 12 * time.Hour, Bucket: 15 * time.Minute, Layout: "15:04"},
|
||||
{Key: "24h", Window: day, Bucket: 30 * time.Minute, Layout: "01-02 15:04"},
|
||||
{Key: "24h", Window: day, Bucket: time.Hour, Source: SourceHourly, Layout: "01-02 15:04"},
|
||||
{Key: "7d", Window: 7 * day, Bucket: 4 * time.Hour, Source: SourceHourly, Layout: "01-02 15:04"},
|
||||
{Key: "30d", Window: 30 * day, Bucket: 12 * time.Hour, Source: SourceHourly, Layout: "2006-01-02 15:04"},
|
||||
{Key: "90d", Window: 90 * day, Bucket: 2 * day, Source: SourceDaily, Layout: "2006-01-02"},
|
||||
|
||||
Reference in new issue
Block a user