// Package datapolicy keeps TimescaleDB's retention policies in line with // the configuration and reports storage use. // // Raw results are compressed after a week and dropped after Raw; the hourly // and daily aggregates outlive them so long charts keep working. All // policies run as TimescaleDB background jobs; this package only sets them. package datapolicy import ( "context" "fmt" "log/slog" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) // Retention sets how long each level of check results is kept. Zero keeps // a level forever. type Retention struct { Raw time.Duration Hourly time.Duration Daily time.Duration } // Relations in the order data flows through them. var relations = []string{"check_results", "check_results_1h", "check_results_1d"} func (r Retention) of(rel string) time.Duration { switch rel { case "check_results": return r.Raw case "check_results_1h": return r.Hourly } return r.Daily } // Validate rejects periods that would break features: charts read the // hourly aggregate for up to 30 days and the daily one for up to a year, // and the hourly aggregate is refreshed from the last three days of raw // data. func (r Retention) Validate() error { day := 24 * time.Hour switch { case r.Raw != 0 && r.Raw < 7*day: return fmt.Errorf("datapolicy: raw results must be kept at least 7 days") case r.Hourly != 0 && r.Hourly < 35*day: return fmt.Errorf("datapolicy: the hourly aggregate must be kept at least 35 days") case r.Daily != 0 && r.Daily < 365*day: return fmt.Errorf("datapolicy: the daily aggregate must be kept at least 365 days") } return nil } // lockID serializes Apply across API replicas starting at the same time. const lockID = 0x75707470 // Apply replaces retention policies whose period differs from want. It is // idempotent and safe to call from several replicas. func Apply(ctx context.Context, pool *pgxpool.Pool, want Retention, log *slog.Logger) error { if err := want.Validate(); err != nil { return err } return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error { if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, lockID); err != nil { return err } current, err := retentionPolicies(ctx, tx) if err != nil { return err } for _, rel := range relations { have, ok := current[rel] target := want.of(rel) if (ok && have == target) || (!ok && target == 0) { continue } if _, err := tx.Exec(ctx, `SELECT remove_retention_policy($1::regclass, if_exists => true)`, rel); err != nil { return fmt.Errorf("datapolicy: removing retention of %s: %w", rel, err) } if target > 0 { if _, err := tx.Exec(ctx, `SELECT add_retention_policy($1::regclass, drop_after => $2::interval)`, rel, interval(target)); err != nil { return fmt.Errorf("datapolicy: setting retention of %s: %w", rel, err) } } log.InfoContext(ctx, "retention policy updated", "relation", rel, "from", have.String(), "to", target.String()) } return nil }) } func retentionPolicies(ctx context.Context, q interface { Query(context.Context, string, ...any) (pgx.Rows, error) }) (map[string]time.Duration, error) { rows, err := q.Query(ctx, ` SELECT hypertable_name, (config->>'drop_after')::interval FROM timescaledb_information.jobs WHERE proc_name = 'policy_retention'`) if err != nil { return nil, err } out := map[string]time.Duration{} for rows.Next() { var name string var d time.Duration if err := rows.Scan(&name, &d); err != nil { return nil, err } out[name] = d } return out, rows.Err() } // interval formats d for Postgres, in days where possible so policies read // as configured. func interval(d time.Duration) string { if d%(24*time.Hour) == 0 { return fmt.Sprintf("%d days", d/(24*time.Hour)) } return fmt.Sprintf("%d seconds", int64(d.Seconds())) }