package db import ( "context" "database/sql" "encoding/json" "fmt" "time" ) // Limits of a RegistryTrend: the runs shown without a period, and the most any // period returns. const ( TrendDefaultRuns = 30 TrendMaxRuns = 200 ) // TrendRun is one finalized run on the X axis of a RegistryTrend. Addresses is // the number of its addresses inside the filter's subnet. type TrendRun struct { ID int64 StartedAt time.Time FinalizedAt *time.Time Addresses int } // TrendPoint is one target or site in one run: Total checks recorded for it and // OK the successful ones. type TrendPoint struct { RunID int64 Key string Total int OK int } // Trend is the checks of one direction (and protocol) per target or site in // each finalized run. Runs are oldest first; Truncated says that more runs // matched than were returned (the oldest were dropped). type Trend struct { Group string // BreakdownTarget or BreakdownSite Truncated bool Runs []TrendRun Points []TrendPoint } // RegistryTrend counts the checks of f.Level (required, else ErrValidation) and // optionally f.Family per target (egress) or site (ingress) in every finalized // run started within [from, to] (UTC calendar days, to inclusive; nil = no // bound). Only Subnet, Level and Family of f count: the run, status and // address filters describe the current state of an address, not a history. // Without a period the last TrendDefaultRuns runs are returned, with one at most // TrendMaxRuns. As in RegistryBreakdown, it counts checks, not addresses, and // reads the address's cycle in the run, so a re-check inside the run replaces // the earlier attempt. func (d *DB) RegistryTrend(ctx context.Context, f RegistryFilter, from, to *time.Time) (*Trend, error) { sl := registrySlice{Level: f.Level, Family: f.Family} if err := sl.validate(); err != nil { return nil, err } if sl.Level == "" { return nil, fmt.Errorf("direction is required: %w", ErrValidation) } t := &Trend{Group: BreakdownTarget} group := "c.target" if sl.Level == LevelIngress { t.Group, group = BreakdownSite, "c.source" } runs, truncated, err := d.trendRuns(ctx, from, to) if err != nil { return nil, err } t.Runs, t.Truncated = runs, truncated if len(t.Runs) == 0 { return t, nil } cond, cargs, ok, err := d.trendRunsCond(ctx, t.Runs, f.Subnet) if err != nil { return nil, err } if !ok { return t, nil } pos := make(map[int64]int, len(t.Runs)) for i, r := range t.Runs { pos[r.ID] = i } // The addresses of each run, for the "of N addresses" of the axis. arows, err := d.QueryContext(ctx, `SELECT rr.run_id, COUNT(*) FROM run_results rr WHERE `+cond+` GROUP BY rr.run_id`, cargs...) if err != nil { return nil, err } defer arows.Close() for arows.Next() { var id int64 var n int if err := arows.Scan(&id, &n); err != nil { return nil, err } t.Runs[pos[id]].Addresses = n } if err := arows.Err(); err != nil { return nil, err } // CROSS JOIN keeps the checks as the inner table: the run's results drive the // lookups over idx_checks_run (run_id, registry_id, cycle_id). sc, scArgs := sl.scopeCond() prows, err := d.QueryContext(ctx, ` SELECT rr.run_id, `+group+`, COUNT(*), COALESCE(SUM(c.success), 0) FROM run_results rr CROSS JOIN checks c ON c.run_id = rr.run_id AND c.registry_id = rr.registry_id AND c.cycle_id = rr.cycle_id WHERE `+cond+` AND `+sc+` GROUP BY rr.run_id, `+group+` ORDER BY `+group+`, rr.run_id`, append(cargs, scArgs...)...) if err != nil { return nil, err } defer prows.Close() for prows.Next() { var p TrendPoint if err := prows.Scan(&p.RunID, &p.Key, &p.Total, &p.OK); err != nil { return nil, err } t.Points = append(t.Points, p) } return t, prows.Err() } // trendRuns selects the runs of a period: finalized ones started within // [from, to] (UTC calendar days, to inclusive; nil = no bound), oldest first. // Without a period the last TrendDefaultRuns runs, with one at most // TrendMaxRuns; truncated says that older runs matched too. The runs of the // trend chart and of the always-pass indicator come from here. func (d *DB) trendRuns(ctx context.Context, from, to *time.Time) (runs []TrendRun, truncated bool, err error) { // started_at is UTC RFC3339Nano text; the bounds without the zone sort just // before every instant of their second, so the comparison is exact. const dayLayout = "2006-01-02T15:04:05" where, args, limit := `state = ?`, []any{RunFinalized}, TrendDefaultRuns if from != nil { where += ` AND started_at >= ?` args = append(args, from.UTC().Truncate(24*time.Hour).Format(dayLayout)) limit = TrendMaxRuns } if to != nil { where += ` AND started_at < ?` args = append(args, to.UTC().Truncate(24*time.Hour).AddDate(0, 0, 1).Format(dayLayout)) limit = TrendMaxRuns } rows, err := d.QueryContext(ctx, `SELECT id, started_at, finalized_at FROM check_runs WHERE `+where+` ORDER BY id DESC LIMIT ?`, append(args, limit+1)...) if err != nil { return nil, false, err } defer rows.Close() for rows.Next() { var r TrendRun var started string var finalized sql.NullString if err := rows.Scan(&r.ID, &started, &finalized); err != nil { return nil, false, err } if r.StartedAt, err = dbToTime(started); err != nil { return nil, false, err } if r.FinalizedAt, err = nullStringToTimePtr(finalized); err != nil { return nil, false, err } runs = append(runs, r) } if err := rows.Err(); err != nil { return nil, false, err } if truncated = len(runs) > limit; truncated { runs = runs[:limit] } // Oldest first, the order of the X axis. for i, j := 0, len(runs)-1; i < j; i, j = i+1, j-1 { runs[i], runs[j] = runs[j], runs[i] } return runs, truncated, nil } // trendRunsCond is the condition over `run_results rr` for the addresses of // runs, inside subnet when it is set. ok is false when the subnet has no // addresses, so nothing can match. func (d *DB) trendRunsCond(ctx context.Context, runs []TrendRun, subnet string) (cond string, args []any, ok bool, err error) { ids := make([]int64, len(runs)) for i, r := range runs { ids[i] = r.ID } runsJSON, err := json.Marshal(ids) if err != nil { return "", nil, false, err } // One JSON parameter per list, as in registryFilterSQL, to stay under SQLite's // bound-variable limit. cond, args = `rr.run_id IN (SELECT value FROM json_each(?))`, []any{string(runsJSON)} if subnet != "" { sub, err := d.subnetIDs(ctx, subnet) if err != nil { return "", nil, false, err } if len(sub) == 0 { return "", nil, false, nil } b, err := json.Marshal(sub) if err != nil { return "", nil, false, err } cond += ` AND rr.registry_id IN (SELECT value FROM json_each(?))` args = append(args, string(b)) } return cond, args, true, nil }