From 97229b91d1a15f0e6f5dca686656c629f19e8a76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 09:50:12 +0100 Subject: [PATCH 1/3] feat(db): compress aggregates, bound daily retention and disable telemetry The hourly and daily aggregates are compressed after 30 and 180 days and the daily aggregate is no longer kept forever. TimescaleDB telemetry is turned off for the database, as self-hosted installations must not report to third parties. Refs #63 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .../migrations/sql/00022_data_lifecycle.sql | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 internal/migrations/sql/00022_data_lifecycle.sql diff --git a/internal/migrations/sql/00022_data_lifecycle.sql b/internal/migrations/sql/00022_data_lifecycle.sql new file mode 100644 index 0000000..399d9f0 --- /dev/null +++ b/internal/migrations/sql/00022_data_lifecycle.sql @@ -0,0 +1,33 @@ +-- +goose Up +-- TimescaleDB reports usage to its vendor by default. Self-hosted +-- installations must not phone home, so it is switched off for this +-- database; the setting applies to new connections and background jobs. +-- +goose StatementBegin +DO $$ +BEGIN + EXECUTE format('ALTER DATABASE %I SET timescaledb.telemetry_level = off', current_database()); +END +$$; +-- +goose StatementEnd + +-- Aggregates are compressed once they are past their refresh window. +ALTER MATERIALIZED VIEW check_results_1h SET (timescaledb.compress = true); +SELECT add_compression_policy('check_results_1h', compress_after => INTERVAL '30 days'); +ALTER MATERIALIZED VIEW check_results_1d SET (timescaledb.compress = true); +SELECT add_compression_policy('check_results_1d', compress_after => INTERVAL '180 days'); + +-- The daily aggregate was kept forever, including data of deleted monitors. +-- The API adjusts all retention periods to its configuration at start. +SELECT add_retention_policy('check_results_1d', INTERVAL '1095 days'); + +-- +goose Down +SELECT remove_retention_policy('check_results_1d', if_exists => true); +SELECT remove_compression_policy('check_results_1d', if_exists => true); +SELECT remove_compression_policy('check_results_1h', if_exists => true); +-- +goose StatementBegin +DO $$ +BEGIN + EXECUTE format('ALTER DATABASE %I RESET timescaledb.telemetry_level', current_database()); +END +$$; +-- +goose StatementEnd -- 2.54.1 From 057e41d5b6fa5da0b3d556cd72f90792cb392ec9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 09:50:12 +0100 Subject: [PATCH 2/3] feat(store): purge old notifications, invitations, tokens and incidents Refs #63 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/store/housekeeping.sql.go | 61 +++++++++++++++++++++++++ internal/store/querier.go | 6 +++ internal/store/queries/housekeeping.sql | 13 ++++++ 3 files changed, 80 insertions(+) create mode 100644 internal/store/housekeeping.sql.go create mode 100644 internal/store/queries/housekeeping.sql diff --git a/internal/store/housekeeping.sql.go b/internal/store/housekeeping.sql.go new file mode 100644 index 0000000..93279ad --- /dev/null +++ b/internal/store/housekeeping.sql.go @@ -0,0 +1,61 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: housekeeping.sql + +package store + +import ( + "context" + "time" +) + +const purgeExpiredTokens = `-- name: PurgeExpiredTokens :execrows +DELETE FROM api_tokens WHERE expires_at < $1 +` + +func (q *Queries) PurgeExpiredTokens(ctx context.Context, expiresAt *time.Time) (int64, error) { + result, err := q.db.Exec(ctx, purgeExpiredTokens, expiresAt) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const purgeIncidents = `-- name: PurgeIncidents :execrows +DELETE FROM incidents WHERE resolved_at < $1 +` + +// Incidents resolved before the oldest data still charted. +func (q *Queries) PurgeIncidents(ctx context.Context, resolvedAt *time.Time) (int64, error) { + result, err := q.db.Exec(ctx, purgeIncidents, resolvedAt) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const purgeInvitations = `-- name: PurgeInvitations :execrows +DELETE FROM invitations WHERE expires_at < $1 OR accepted_at < $1 +` + +func (q *Queries) PurgeInvitations(ctx context.Context, expiresAt time.Time) (int64, error) { + result, err := q.db.Exec(ctx, purgeInvitations, expiresAt) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const purgeNotifications = `-- name: PurgeNotifications :execrows +DELETE FROM notifications WHERE status IN ('sent', 'failed') AND created_at < $1 +` + +// Delivered and given-up notifications; pending ones are still being worked. +func (q *Queries) PurgeNotifications(ctx context.Context, createdAt time.Time) (int64, error) { + result, err := q.db.Exec(ctx, purgeNotifications, createdAt) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} diff --git a/internal/store/querier.go b/internal/store/querier.go index e3135be..c64f2a0 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -151,6 +151,12 @@ type Querier interface { OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error) OpenIncidents(ctx context.Context) ([]Incident, error) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) + PurgeExpiredTokens(ctx context.Context, expiresAt *time.Time) (int64, error) + // Incidents resolved before the oldest data still charted. + PurgeIncidents(ctx context.Context, resolvedAt *time.Time) (int64, error) + PurgeInvitations(ctx context.Context, expiresAt time.Time) (int64, error) + // Delivered and given-up notifications; pending ones are still being worked. + PurgeNotifications(ctx context.Context, createdAt time.Time) (int64, error) // Raw results bucketed by width since a point in time, for short ranges. RangeBuckets(ctx context.Context, arg RangeBucketsParams) ([]RangeBucketsRow, error) // The daily aggregate rebucketed by width, for ranges of months. diff --git a/internal/store/queries/housekeeping.sql b/internal/store/queries/housekeeping.sql new file mode 100644 index 0000000..f930398 --- /dev/null +++ b/internal/store/queries/housekeeping.sql @@ -0,0 +1,13 @@ +-- name: PurgeNotifications :execrows +-- Delivered and given-up notifications; pending ones are still being worked. +DELETE FROM notifications WHERE status IN ('sent', 'failed') AND created_at < $1; + +-- name: PurgeInvitations :execrows +DELETE FROM invitations WHERE expires_at < $1 OR accepted_at < $1; + +-- name: PurgeExpiredTokens :execrows +DELETE FROM api_tokens WHERE expires_at < $1; + +-- name: PurgeIncidents :execrows +-- Incidents resolved before the oldest data still charted. +DELETE FROM incidents WHERE resolved_at < $1; -- 2.54.1 From 538e9358c3db4c3093f175c75587d9199f30fece Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 09:50:12 +0100 Subject: [PATCH 3/3] feat(api): configurable retention, housekeeping and storage overview UPTIME_RETENTION_RAW, _HOURLY and _DAILY set TimescaleDB's retention policies, applied by "api migrate up" with owner rights and on start; periods too short for the charts are rejected. An hourly job deletes delivered notifications, stale invitations and expired API tokens after UPTIME_RETENTION_HOUSEKEEPING and resolved incidents together with the daily aggregate. The admin panel shows size, compression, retention and background job status of each storage level. Closes #63 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .env.example | 9 + cmd/api/main.go | 34 +- internal/api/housekeeping.go | 119 ++++++ internal/api/housekeeping_test.go | 138 +++++++ internal/api/pages.go | 8 +- internal/config/config.go | 13 + internal/datapolicy/datapolicy.go | 123 +++++++ internal/datapolicy/datapolicy_test.go | 89 +++++ internal/datapolicy/stats.go | 128 +++++++ internal/i18n/i18n_test.go | 2 + internal/i18n/locales/de.json | 26 ++ internal/i18n/locales/en.json | 26 ++ internal/tenant/tenant.go | 4 + internal/web/regions.templ | 3 +- internal/web/regions_templ.go | 6 +- internal/web/storage.templ | 130 +++++++ internal/web/storage_templ.go | 491 +++++++++++++++++++++++++ 17 files changed, 1342 insertions(+), 7 deletions(-) create mode 100644 internal/api/housekeeping.go create mode 100644 internal/api/housekeeping_test.go create mode 100644 internal/datapolicy/datapolicy.go create mode 100644 internal/datapolicy/datapolicy_test.go create mode 100644 internal/datapolicy/stats.go create mode 100644 internal/web/storage.templ create mode 100644 internal/web/storage_templ.go diff --git a/.env.example b/.env.example index 6c27465..4d6aac4 100644 --- a/.env.example +++ b/.env.example @@ -23,6 +23,15 @@ UPTIME_API_URL=http://localhost:8080 UPTIME_TEST_DATABASE_URL=postgres://uptime:uptime@localhost:5432/uptime_test?sslmode=disable UPTIME_TEST_REDIS_URL=redis://localhost:6379/15 +# Data retention (0 keeps forever). Raw results feed charts up to 24h, the +# hourly aggregate 7d and 30d, the daily aggregate up to a year; resolved +# incidents follow the daily aggregate. +# UPTIME_RETENTION_RAW=2160h +# UPTIME_RETENTION_HOURLY=9600h +# UPTIME_RETENTION_DAILY=26280h +# Delivered notifications, expired invitations and expired API tokens. +# UPTIME_RETENTION_HOUSEKEEPING=720h + # Status page server: hosts serving pages by slug; enable TLS for custom domains. UPTIME_STATUSPAGE_URL=http://localhost:8082 UPTIME_STATUSPAGE_HOSTS=localhost diff --git a/cmd/api/main.go b/cmd/api/main.go index a0836ac..c093638 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -9,8 +9,11 @@ import ( "os" "time" + "github.com/jackc/pgx/v5/pgxpool" + "git.zb-server.de/ZB-Server/uptimesebi/internal/api" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/datapolicy" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" "git.zb-server.de/ZB-Server/uptimesebi/internal/notify" @@ -42,7 +45,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { if len(args) > 0 { switch args[0] { case "migrate": - return migrate(ctx, log, cfg.DatabaseURL, args[1:]) + return migrate(ctx, log, cfg, args[1:]) case "admin", "agent", "region": return admin(ctx, cfg, args) case "serve": @@ -54,6 +57,9 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { if err := cfg.Validate(); err != nil { return err } + if err := retentionOf(cfg).Validate(); err != nil { + return err + } keys, err := sealed.Parse(cfg.SecretKeys) if err != nil { return err @@ -79,11 +85,13 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { srv.Mount(r) go srv.RunScheduler(ctx) go srv.RunNotifier(ctx) + go srv.RunHousekeeping(ctx) return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout) } -func migrate(ctx context.Context, log *slog.Logger, dsn string, args []string) error { +func migrate(ctx context.Context, log *slog.Logger, cfg config.API, args []string) error { + dsn := cfg.DatabaseURL if dsn == "" { return errors.New("UPTIME_DATABASE_URL is required") } @@ -98,10 +106,13 @@ func migrate(ctx context.Context, log *slog.Logger, dsn string, args []string) e for _, r := range res { log.Info("migration applied", "migration", r.Source.Version, "file", r.Source.Path, "duration_ms", r.Duration.Milliseconds()) } - if err == nil && len(res) == 0 { + if err != nil { + return err + } + if len(res) == 0 { log.Info("schema up to date") } - return err + return applyRetention(ctx, log, cfg) case "down": r, err := migrations.Down(ctx, dsn) if r != nil { @@ -117,3 +128,18 @@ func migrate(ctx context.Context, log *slog.Logger, dsn string, args []string) e } return errors.New("unknown migrate command " + cmd) } + +func retentionOf(cfg config.API) datapolicy.Retention { + return datapolicy.Retention{Raw: cfg.Retention.Raw, Hourly: cfg.Retention.Hourly, Daily: cfg.Retention.Daily} +} + +// applyRetention runs with the migration's owner rights, which changing +// TimescaleDB policies needs. +func applyRetention(ctx context.Context, log *slog.Logger, cfg config.API) error { + pool, err := pgxpool.New(ctx, cfg.DatabaseURL) + if err != nil { + return err + } + defer pool.Close() + return datapolicy.Apply(ctx, pool, retentionOf(cfg), log) +} diff --git a/internal/api/housekeeping.go b/internal/api/housekeeping.go new file mode 100644 index 0000000..f0cc8f8 --- /dev/null +++ b/internal/api/housekeeping.go @@ -0,0 +1,119 @@ +package api + +import ( + "context" + "fmt" + "slices" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/datapolicy" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" + "git.zb-server.de/ZB-Server/uptimesebi/internal/web" +) + +func (s *Server) retention() datapolicy.Retention { + r := s.cfg.Retention + return datapolicy.Retention{Raw: r.Raw, Hourly: r.Hourly, Daily: r.Daily} +} + +// RunHousekeeping aligns TimescaleDB's retention with the configuration and +// then purges rows TimescaleDB does not manage, hourly, until ctx ends. +// Every replica runs it; the deletes are idempotent. +func (s *Server) RunHousekeeping(ctx context.Context) { + if err := datapolicy.Apply(ctx, s.db.Pool(), s.retention(), s.log); err != nil { + // The API role may not own the tables; "api migrate up" applies the + // policies as owner. + s.log.WarnContext(ctx, "applying retention policies failed", "error", err) + } + tick := time.NewTicker(time.Hour) + defer tick.Stop() + for { + if err := s.Housekeep(ctx, time.Now()); err != nil && ctx.Err() == nil { + s.log.ErrorContext(ctx, "housekeeping failed", "error", err) + } + select { + case <-ctx.Done(): + return + case <-tick.C: + } + } +} + +// Housekeep deletes delivered notifications, stale invitations, expired API +// tokens and incidents older than the daily aggregate. +func (s *Server) Housekeep(ctx context.Context, now time.Time) error { + keep := s.cfg.Retention + var counts [4]int64 + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + if keep.Housekeeping > 0 { + before := now.Add(-keep.Housekeeping) + if counts[0], err = q.PurgeNotifications(ctx, before); err != nil { + return err + } + if counts[1], err = q.PurgeInvitations(ctx, before); err != nil { + return err + } + if counts[2], err = q.PurgeExpiredTokens(ctx, &before); err != nil { + return err + } + } + if keep.Daily > 0 { + before := now.Add(-keep.Daily) + counts[3], err = q.PurgeIncidents(ctx, &before) + } + return err + }) + if err == nil && counts != [4]int64{} { + s.log.InfoContext(ctx, "housekeeping purged rows", + "notifications", counts[0], "invitations", counts[1], "api_tokens", counts[2], "incidents", counts[3]) + } + return err +} + +func storageView(c *gin.Context, st datapolicy.Stats) web.StorageView { + ctx := c.Request.Context() + var v web.StorageView + for _, r := range st.Relations { + l := web.StorageLevel{ + Key: strings.TrimPrefix(strings.TrimPrefix(r.Name, "check_results"), "_"), + Size: web.Bytes(r.TotalBytes), + Chunks: fmt.Sprintf("%d / %d", r.CompressedChunks, r.Chunks), + Retention: web.Days(ctx, r.Retention), + CompressAfter: "–", + } + if l.Key == "" { + l.Key = "raw" + } + if r.CompressAfter > 0 { + l.CompressAfter = web.Days(ctx, r.CompressAfter) + } + if r.AfterBytes > 0 { + l.Compressed = fmt.Sprintf("%s → %s", web.Bytes(r.BeforeBytes), web.Bytes(r.AfterBytes)) + } + v.Levels = append(v.Levels, l) + } + const layout = "2006-01-02 15:04" + for _, j := range st.Jobs { + sj := web.StorageJob{ + Name: strings.TrimPrefix(j.Proc, "policy_"), Relation: j.Relation, + OK: j.LastStatus != "Failed", Failures: j.Failures, LastRun: "–", NextRun: "–", + } + if j.LastRun != nil { + sj.LastRun = j.LastRun.Local().Format(layout) + } + if j.NextRun != nil { + sj.NextRun = j.NextRun.Local().Format(layout) + } + v.Jobs = append(v.Jobs, sj) + } + for name, size := range st.TableBytes { + v.Tables = append(v.Tables, web.StorageTable{Name: name, Size: web.Bytes(size)}) + } + slices.SortFunc(v.Tables, func(a, b web.StorageTable) int { return strings.Compare(a.Name, b.Name) }) + return v +} diff --git a/internal/api/housekeeping_test.go b/internal/api/housekeeping_test.go new file mode 100644 index 0000000..7421d3b --- /dev/null +++ b/internal/api/housekeeping_test.go @@ -0,0 +1,138 @@ +package api_test + +import ( + "context" + "net/http" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +func TestHousekeepingPurgesOnlyOldRows(t *testing.T) { + e := newEnvWith(t, func(c *config.API) { + c.Retention = config.Retention{Daily: 365 * 24 * time.Hour, Housekeeping: 30 * 24 * time.Hour} + }) + _, region := e.platformChecker(t, uniq("eu-")) + owner := e.browser(t) + owner.signup("o@"+uniq("hk")+".test", uniq("hk-")) + st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{ + "name": "M", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region}, + }) + if st != http.StatusCreated { + t.Fatal(body) + } + monitor := uuid.MustParse(body["id"].(string)) + org := uuid.MustParse(owner.orgID()) + user := owner.userIDSelf() + role := uuid.MustParse(owner.roleID("viewer")) + + ctx := context.Background() + now := time.Now() + old, fresh := now.Add(-40*24*time.Hour), now.Add(-time.Hour) + ancient := now.Add(-400 * 24 * time.Hour) + var oldInc, freshInc, ancientInc uuid.UUID + err := e.asSystem(t, func(tx pgx.Tx) error { + var channel uuid.UUID + if err := tx.QueryRow(ctx, `INSERT INTO notification_channels (org_id, name, type, config) VALUES ($1, 'c', 'webhook', '{}') RETURNING id`, org).Scan(&channel); err != nil { + return err + } + for _, inc := range []struct { + id *uuid.UUID + started time.Time + }{{&ancientInc, ancient}, {&oldInc, old}, {&freshInc, fresh}} { + if err := tx.QueryRow(ctx, `INSERT INTO incidents (org_id, monitor_id, started_at, resolved_at) VALUES ($1, $2, $3::timestamptz, $3::timestamptz + interval '5 minutes') RETURNING id`, + org, monitor, inc.started).Scan(inc.id); err != nil { + return err + } + } + for _, n := range []struct { + inc uuid.UUID + status string + created time.Time + }{{oldInc, "sent", old}, {freshInc, "sent", fresh}} { + if _, err := tx.Exec(ctx, `INSERT INTO notifications (org_id, channel_id, incident_id, event, status, created_at) VALUES ($1, $2, $3, 'opened', $4, $5)`, + org, channel, n.inc, n.status, n.created); err != nil { + return err + } + } + if _, err := tx.Exec(ctx, `INSERT INTO notifications (org_id, channel_id, incident_id, event, status, created_at) VALUES ($1, $2, $3, 'resolved', 'pending', $4)`, + org, channel, oldInc, old); err != nil { + return err + } + for i, exp := range []time.Time{old, now.Add(24 * time.Hour)} { + if _, err := tx.Exec(ctx, `INSERT INTO invitations (org_id, email, role_id, token_hash, expires_at) VALUES ($1, $2, $3, $4, $5)`, + org, uniq("i")+"@x.test", role, []byte(uniq("h")), exp); err != nil { + return err + } + if _, err := tx.Exec(ctx, `INSERT INTO api_tokens (org_id, user_id, name, token_hash, prefix, permissions, expires_at) VALUES ($1, $2, $3, $4, 'usk_x', '{}', $5)`, + org, user, "t"+string(rune('a'+i)), []byte(uniq("t")), exp); err != nil { + return err + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + + if err := e.api.Housekeep(ctx, now); err != nil { + t.Fatalf("Housekeep() = %v", err) + } + + count := func(query string) int { + var n int + _ = e.asSystem(t, func(tx pgx.Tx) error { return tx.QueryRow(ctx, query, org).Scan(&n) }) + return n + } + for query, want := range map[string]int{ + `SELECT count(*) FROM notifications WHERE org_id = $1 AND status = 'sent'`: 1, + `SELECT count(*) FROM notifications WHERE org_id = $1 AND status = 'pending'`: 1, + `SELECT count(*) FROM invitations WHERE org_id = $1`: 1, + `SELECT count(*) FROM api_tokens WHERE org_id = $1 AND expires_at IS NOT NULL`: 1, + `SELECT count(*) FROM incidents WHERE org_id = $1`: 2, + } { + if got := count(query); got != want { + t.Errorf("%s = %d, want %d", query, got, want) + } + } +} + +func TestAdminSeesStorage(t *testing.T) { + e := newEnv(t) + a := e.browser(t) + a.signup("a@"+uniq("st")+".test", uniq("st-")) + err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error { + return q.MakeAdmin(context.Background(), a.userIDSelf()) + }) + if err != nil { + t.Fatal(err) + } + st, _, html := a.page("/admin") + if st != http.StatusOK { + t.Fatalf("GET /admin = %d", st) + } + for _, want := range []string{"Data storage", "Raw results", "Daily aggregate", "Background jobs", "Compression"} { + if !strings.Contains(html, want) { + t.Errorf("admin page lacks %q", want) + } + } +} + +// asSystem runs fn in a transaction that bypasses tenant isolation. +func (e *env) asSystem(t *testing.T, fn func(pgx.Tx) error) error { + t.Helper() + ctx := context.Background() + return pgx.BeginFunc(ctx, e.dbPool, func(tx pgx.Tx) error { + if _, err := tx.Exec(ctx, `SELECT set_config('app.scope', 'system', true)`); err != nil { + return err + } + return fn(tx) + }) +} diff --git a/internal/api/pages.go b/internal/api/pages.go index 6102e73..3538dc6 100644 --- a/internal/api/pages.go +++ b/internal/api/pages.go @@ -14,6 +14,7 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/authz" + "git.zb-server.de/ZB-Server/uptimesebi/internal/datapolicy" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" @@ -458,7 +459,12 @@ func (s *Server) adminPage(c *gin.Context) { internalError(c, err) return } - web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v)) + stats, err := datapolicy.Collect(ctx, s.db.Pool()) + if err != nil { + internalError(c, err) + return + } + web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats))) } func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, agents []store.ListAgentsRow, apiBase, next string, manageable func(store.Region) bool) (web.RegionsView, error) { diff --git a/internal/config/config.go b/internal/config/config.go index 2acff85..3deaa02 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -87,6 +87,19 @@ type API struct { // StatusPageURL is where the platform's status page servers are // reachable; the console links pages as /. StatusPageURL string `env:"UPTIME_STATUSPAGE_URL" envDefault:"http://localhost:8082"` + Retention Retention +} + +// Retention sets how long data is kept. Zero keeps it forever. +type Retention struct { + // Raw check results; charts up to 24h and the recent checks list read them. + Raw time.Duration `env:"UPTIME_RETENTION_RAW" envDefault:"2160h"` + // Hourly aggregate, read by 7d and 30d charts. + Hourly time.Duration `env:"UPTIME_RETENTION_HOURLY" envDefault:"9600h"` + // Daily aggregate and resolved incidents, read by charts up to a year. + Daily time.Duration `env:"UPTIME_RETENTION_DAILY" envDefault:"26280h"` + // Delivered notifications, expired invitations and expired API tokens. + Housekeeping time.Duration `env:"UPTIME_RETENTION_HOUSEKEEPING" envDefault:"720h"` } // SSOAllowPrivate resolves SSOPrivateNetworks. diff --git a/internal/datapolicy/datapolicy.go b/internal/datapolicy/datapolicy.go new file mode 100644 index 0000000..0411097 --- /dev/null +++ b/internal/datapolicy/datapolicy.go @@ -0,0 +1,123 @@ +// 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())) +} diff --git a/internal/datapolicy/datapolicy_test.go b/internal/datapolicy/datapolicy_test.go new file mode 100644 index 0000000..e6e0969 --- /dev/null +++ b/internal/datapolicy/datapolicy_test.go @@ -0,0 +1,89 @@ +package datapolicy + +import ( + "context" + "log/slog" + "os" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" +) + +const day = 24 * time.Hour + +func TestValidate(t *testing.T) { + for _, tc := range []struct { + r Retention + ok bool + }{ + {Retention{}, true}, + {Retention{Raw: 90 * day, Hourly: 400 * day, Daily: 365 * day}, true}, + {Retention{Raw: 6 * day}, false}, + {Retention{Hourly: 30 * day}, false}, + {Retention{Daily: 364 * day}, false}, + } { + if err := tc.r.Validate(); (err == nil) != tc.ok { + t.Errorf("%+v.Validate() = %v, want ok=%t", tc.r, err, tc.ok) + } + } +} + +func testPool(t *testing.T) *pgxpool.Pool { + t.Helper() + dsn := os.Getenv("UPTIME_TEST_DATABASE_URL") + if dsn == "" { + t.Skip("UPTIME_TEST_DATABASE_URL must be set") + } + ctx := context.Background() + if _, err := migrations.Up(ctx, dsn); err != nil { + t.Fatal(err) + } + pool, err := pgxpool.New(ctx, dsn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + return pool +} + +func TestApply(t *testing.T) { + pool := testPool(t) + ctx := context.Background() + log := slog.New(slog.DiscardHandler) + defaults := Retention{Raw: 90 * day, Hourly: 400 * day, Daily: 1095 * day} + t.Cleanup(func() { _ = Apply(ctx, pool, defaults, log) }) + + want := Retention{Raw: 30 * day, Hourly: 0, Daily: 730 * day} + for range 2 { + if err := Apply(ctx, pool, want, log); err != nil { + t.Fatalf("Apply() = %v", err) + } + } + got, err := retentionPolicies(ctx, pool) + if err != nil { + t.Fatal(err) + } + if got["check_results"] != want.Raw || got["check_results_1d"] != want.Daily { + t.Errorf("policies = %v, want raw %v and daily %v", got, want.Raw, want.Daily) + } + if _, ok := got["check_results_1h"]; ok { + t.Error("hourly aggregate still has a retention policy after setting it to forever") + } + if err := Apply(ctx, pool, Retention{Raw: day}, log); err == nil { + t.Error("Apply() accepted one day of raw results") + } + + st, err := Collect(ctx, pool) + if err != nil { + t.Fatalf("Collect() = %v", err) + } + if len(st.Relations) != 3 || st.Relations[0].Name != "check_results" || st.Relations[0].Retention != want.Raw { + t.Errorf("Collect().Relations = %+v", st.Relations) + } + if len(st.Jobs) == 0 { + t.Error("Collect() found no background jobs") + } +} diff --git a/internal/datapolicy/stats.go b/internal/datapolicy/stats.go new file mode 100644 index 0000000..4559e92 --- /dev/null +++ b/internal/datapolicy/stats.go @@ -0,0 +1,128 @@ +package datapolicy + +import ( + "context" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +// RelationStats describes one level of check result storage. +type RelationStats struct { + Name string + // TotalBytes includes indexes and compressed data. + TotalBytes int64 + // BeforeBytes and AfterBytes cover compressed chunks only. + BeforeBytes int64 + AfterBytes int64 + Chunks int64 + CompressedChunks int64 + Retention time.Duration + CompressAfter time.Duration +} + +// JobStats is the last run of a TimescaleDB background job. +type JobStats struct { + ID int64 + Proc string + Relation string + LastStatus string + LastRun *time.Time + NextRun *time.Time + Failures int64 +} + +// Stats is a storage overview for the admin panel. +type Stats struct { + Relations []RelationStats + Jobs []JobStats + // TableBytes lists the largest regular tables. + TableBytes map[string]int64 +} + +// Collect gathers storage statistics. Aggregates are measured through their +// materialization hypertables. +func Collect(ctx context.Context, pool *pgxpool.Pool) (Stats, error) { + var s Stats + rows, err := pool.Query(ctx, ` + WITH rel AS ( + SELECT 'check_results'::text AS name, 'public'::text AS schema, 'check_results'::text AS ht + UNION ALL + SELECT view_name::text, materialization_hypertable_schema::text, materialization_hypertable_name::text + FROM timescaledb_information.continuous_aggregates + WHERE view_name IN ('check_results_1h', 'check_results_1d') + ) + SELECT rel.name, + hypertable_size(format('%I.%I', rel.schema, rel.ht)::regclass), + coalesce(cs.before_compression_total_bytes, 0), + coalesce(cs.after_compression_total_bytes, 0), + coalesce(cs.total_chunks, 0), + coalesce(cs.number_compressed_chunks, 0), + (SELECT (config->>'drop_after')::interval FROM timescaledb_information.jobs + WHERE proc_name = 'policy_retention' AND hypertable_name = rel.name), + (SELECT (config->>'compress_after')::interval FROM timescaledb_information.jobs + WHERE proc_name = 'policy_compression' AND hypertable_name = rel.name) + FROM rel + LEFT JOIN LATERAL hypertable_compression_stats(format('%I.%I', rel.schema, rel.ht)::regclass) cs ON true + ORDER BY array_position(ARRAY['check_results', 'check_results_1h', 'check_results_1d'], rel.name)`) + if err != nil { + return s, err + } + for rows.Next() { + var r RelationStats + var retention, compress *time.Duration + if err := rows.Scan(&r.Name, &r.TotalBytes, &r.BeforeBytes, &r.AfterBytes, &r.Chunks, &r.CompressedChunks, &retention, &compress); err != nil { + return s, err + } + if retention != nil { + r.Retention = *retention + } + if compress != nil { + r.CompressAfter = *compress + } + s.Relations = append(s.Relations, r) + } + if err := rows.Err(); err != nil { + return s, err + } + + rows, err = pool.Query(ctx, ` + SELECT j.job_id, j.proc_name, coalesce(j.hypertable_name, ''), coalesce(st.last_run_status, ''), + st.last_run_started_at, st.next_start, coalesce(st.total_failures, 0) + FROM timescaledb_information.jobs j + LEFT JOIN timescaledb_information.job_stats st USING (job_id) + WHERE j.proc_name LIKE 'policy_%' AND j.proc_name <> 'policy_telemetry' + ORDER BY j.hypertable_name NULLS FIRST, j.proc_name`) + if err != nil { + return s, err + } + for rows.Next() { + var j JobStats + if err := rows.Scan(&j.ID, &j.Proc, &j.Relation, &j.LastStatus, &j.LastRun, &j.NextRun, &j.Failures); err != nil { + return s, err + } + s.Jobs = append(s.Jobs, j) + } + if err := rows.Err(); err != nil { + return s, err + } + + s.TableBytes = map[string]int64{} + rows, err = pool.Query(ctx, ` + SELECT relname::text, pg_total_relation_size(c.oid) + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relkind = 'r' + AND relname IN ('incidents', 'notifications', 'monitors', 'agent_storage', 'invitations', 'api_tokens')`) + if err != nil { + return s, err + } + for rows.Next() { + var name string + var size int64 + if err := rows.Scan(&name, &size); err != nil { + return s, err + } + s.TableBytes[name] = size + } + return s, rows.Err() +} diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index 403782a..d6ddf30 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -155,6 +155,8 @@ func TestDynamicFamilies(t *testing.T) { "agents.kind_": {"checker", "statuspage"}, "page.status.": {"operational", "degraded", "outage", "unknown"}, "page.component.": {"operational", "degraded", "outage", "unknown"}, + "storage.level_": {"raw", "1h", "1d"}, + "storage.job_": {"compression", "retention", "refresh_continuous_aggregate", "job_stat_history_retention"}, } for prefix, values := range families { for _, v := range values { diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index a7e38a7..4929fc4 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -370,6 +370,32 @@ "status.paused": "pausiert", "status.unknown": "keine Daten", "status.up": "erreichbar", + "storage.chunks": "Komprimierte Chunks", + "storage.compress_after": "Komprimieren nach", + "storage.days": { + "one": "{{.Count}} Tag", + "other": "{{.Count}} Tage" + }, + "storage.failures": { + "one": "{{.Count}} Fehlschlag", + "other": "{{.Count}} Fehlschläge" + }, + "storage.forever": "nie", + "storage.intro": "Check-Ergebnisse werden nach einiger Zeit komprimiert und nach Ablauf ihrer Aufbewahrungsdauer gelöscht. Lange Diagramme lesen die stündlichen und täglichen Aggregate, die länger aufbewahrt werden. Die Aufbewahrung wird über UPTIME_RETENTION_* eingestellt und beim Start sowie von „api migrate up“ angewendet.", + "storage.job_compression": "Kompression", + "storage.job_job_stat_history_retention": "Job-Historie aufräumen", + "storage.job_refresh_continuous_aggregate": "Aggregat-Aktualisierung", + "storage.job_retention": "Aufbewahrung", + "storage.jobs": "Hintergrundjobs", + "storage.last_run": "Letzter Lauf", + "storage.level": "Stufe", + "storage.level_1d": "Tagesaggregat", + "storage.level_1h": "Stundenaggregat", + "storage.level_raw": "Rohdaten", + "storage.next_run": "Nächster Lauf", + "storage.retention": "Löschen nach", + "storage.size": "Größe", + "storage.title": "Datenspeicher", "tokens.copy_now": "Kopiere den Token jetzt. Er wird nicht erneut angezeigt.", "tokens.create": "Token erstellen", "tokens.created": "Erstellt", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index ac8afe2..ca2da4a 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -370,6 +370,32 @@ "status.paused": "paused", "status.unknown": "no data", "status.up": "up", + "storage.chunks": "Compressed chunks", + "storage.compress_after": "Compress after", + "storage.days": { + "one": "{{.Count}} day", + "other": "{{.Count}} days" + }, + "storage.failures": { + "one": "{{.Count}} failure", + "other": "{{.Count}} failures" + }, + "storage.forever": "never", + "storage.intro": "Check results are compressed after a while and deleted after their retention period. Long charts read the hourly and daily aggregates, which are kept longer. Retention is set with UPTIME_RETENTION_* and applied on start and by \"api migrate up\".", + "storage.job_compression": "Compression", + "storage.job_job_stat_history_retention": "Job history cleanup", + "storage.job_refresh_continuous_aggregate": "Aggregate refresh", + "storage.job_retention": "Retention", + "storage.jobs": "Background jobs", + "storage.last_run": "Last run", + "storage.level": "Level", + "storage.level_1d": "Daily aggregate", + "storage.level_1h": "Hourly aggregate", + "storage.level_raw": "Raw results", + "storage.next_run": "Next run", + "storage.retention": "Delete after", + "storage.size": "Size", + "storage.title": "Data storage", "tokens.copy_now": "Copy the token now. It will not be shown again.", "tokens.create": "Create token", "tokens.created": "Created", diff --git a/internal/tenant/tenant.go b/internal/tenant/tenant.go index b9376e7..a779653 100644 --- a/internal/tenant/tenant.go +++ b/internal/tenant/tenant.go @@ -47,6 +47,10 @@ type DB struct{ pool *pgxpool.Pool } // New returns a DB using pool. func New(pool *pgxpool.Pool) *DB { return &DB{pool: pool} } +// Pool returns the underlying pool for queries outside any tenant table, +// such as TimescaleDB's catalog. +func (d *DB) Pool() *pgxpool.Pool { return d.pool } + // Tx runs fn in a transaction whose row-level-security settings come from s. // The transaction commits if fn returns nil and rolls back otherwise. func (d *DB) Tx(ctx context.Context, s Scope, fn func(*store.Queries) error) error { diff --git a/internal/web/regions.templ b/internal/web/regions.templ index 8135c73..e6e7d3a 100644 --- a/internal/web/regions.templ +++ b/internal/web/regions.templ @@ -143,9 +143,10 @@ templ RegionsPage(p Page, me Me, v RegionsView) { } } -templ AdminPage(p Page, me Me, v RegionsView) { +templ AdminPage(p Page, me Me, v RegionsView, storage StorageView) { @consoleShell(p, me) { @settingsHeading("admin.title", "admin.intro") @regionsBody(v) + @storageSection(storage) } } diff --git a/internal/web/regions_templ.go b/internal/web/regions_templ.go index 2c17247..8ea5f18 100644 --- a/internal/web/regions_templ.go +++ b/internal/web/regions_templ.go @@ -696,7 +696,7 @@ func RegionsPage(p Page, me Me, v RegionsView) templ.Component { }) } -func AdminPage(p Page, me Me, v RegionsView) templ.Component { +func AdminPage(p Page, me Me, v RegionsView, storage StorageView) templ.Component { return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { @@ -733,6 +733,10 @@ func AdminPage(p Page, me Me, v RegionsView) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } + templ_7745c5c3_Err = storageSection(storage).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } return nil }) templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var38), templ_7745c5c3_Buffer) diff --git a/internal/web/storage.templ b/internal/web/storage.templ new file mode 100644 index 0000000..7eb84f2 --- /dev/null +++ b/internal/web/storage.templ @@ -0,0 +1,130 @@ +package web + +import ( + "context" + "fmt" + "time" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" +) + +// StorageView summarizes how check data is stored and cleaned up. +type StorageView struct { + Levels []StorageLevel + Jobs []StorageJob + Tables []StorageTable +} + +// StorageLevel is raw results or one of the aggregates. +type StorageLevel struct { + Key string + Size string + Compressed string + Chunks string + Retention string + CompressAfter string +} + +// StorageJob is a TimescaleDB background job. +type StorageJob struct { + Name string + Relation string + OK bool + LastRun string + NextRun string + Failures int64 +} + +// StorageTable is a regular table and its size. +type StorageTable struct { + Name string + Size string +} + +// Bytes formats n in binary units. +func Bytes(n int64) string { + const unit = 1024 + if n < unit { + return fmt.Sprintf("%d B", n) + } + div, exp := int64(unit), 0 + for m := n / unit; m >= unit; m /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp]) +} + +// Days formats a retention period; zero means forever. +func Days(ctx context.Context, d time.Duration) string { + if d == 0 { + return i18n.T(ctx, "storage.forever") + } + if d%(24*time.Hour) == 0 { + return i18n.T(ctx, "storage.days", "Count", int(d/(24*time.Hour))) + } + return d.String() +} + +templ storageSection(v StorageView) { +
+ @sectionHeading("storage.title") +

{ i18n.T(ctx, "storage.intro") }

+
+ + + + + + + + + + + + for _, l := range v.Levels { + + + + + + + + } + +
{ i18n.T(ctx, "storage.level") }{ i18n.T(ctx, "storage.size") }{ i18n.T(ctx, "storage.chunks") }{ i18n.T(ctx, "storage.compress_after") }{ i18n.T(ctx, "storage.retention") }
{ i18n.T(ctx, "storage.level_" + l.Key) } + { l.Size } + if l.Compressed != "" { + { " · " + l.Compressed } + } + { l.Chunks }{ l.CompressAfter }{ l.Retention }
+
+ if len(v.Tables) > 0 { +

+ for i, t := range v.Tables { + if i > 0 { + { " · " } + } + { t.Name + " " + t.Size } + } +

+ } +

{ i18n.T(ctx, "storage.jobs") }

+
    + for _, j := range v.Jobs { +
  • + + + { i18n.T(ctx, "storage.job_" + j.Name) } + { j.Relation } + if j.Failures > 0 { + { i18n.T(ctx, "storage.failures", "Count", j.Failures) } + } + + { j.LastRun } + +
  • + } +
+
+} diff --git a/internal/web/storage_templ.go b/internal/web/storage_templ.go new file mode 100644 index 0000000..19de28d --- /dev/null +++ b/internal/web/storage_templ.go @@ -0,0 +1,491 @@ +// Code generated by templ - DO NOT EDIT. + +// templ: version: v0.3.1118 + +package web + +//lint:file-ignore SA4006 This context is only used if a nested component is present. + +import "github.com/a-h/templ" +import templruntime "github.com/a-h/templ/runtime" + +import ( + "context" + "fmt" + "time" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" +) + +// StorageView summarizes how check data is stored and cleaned up. +type StorageView struct { + Levels []StorageLevel + Jobs []StorageJob + Tables []StorageTable +} + +// StorageLevel is raw results or one of the aggregates. +type StorageLevel struct { + Key string + Size string + Compressed string + Chunks string + Retention string + CompressAfter string +} + +// StorageJob is a TimescaleDB background job. +type StorageJob struct { + Name string + Relation string + OK bool + LastRun string + NextRun string + Failures int64 +} + +// StorageTable is a regular table and its size. +type StorageTable struct { + Name string + Size string +} + +// Bytes formats n in binary units. +func Bytes(n int64) string { + const unit = 1024 + if n < unit { + return fmt.Sprintf("%d B", n) + } + div, exp := int64(unit), 0 + for m := n / unit; m >= unit; m /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp]) +} + +// Days formats a retention period; zero means forever. +func Days(ctx context.Context, d time.Duration) string { + if d == 0 { + return i18n.T(ctx, "storage.forever") + } + if d%(24*time.Hour) == 0 { + return i18n.T(ctx, "storage.days", "Count", int(d/(24*time.Hour))) + } + return d.String() +} + +func storageSection(v StorageView) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("storage.title").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var2 string + templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "storage.intro")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 72, Col: 77} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, l := range v.Levels { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var3 string + templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "storage.level")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 77, Col: 70} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var4 string + templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "storage.size")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 78, Col: 69} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var5 string + templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "storage.chunks")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 79, Col: 71} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var6 string + templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "storage.compress_after")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 80, Col: 79} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var7 string + templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "storage.retention")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 81, Col: 69} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var8 string + templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "storage.level_"+l.Key)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 87, Col: 68} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var9 string + templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(l.Size) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 89, Col: 16} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if l.Compressed != "" { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var10 string + templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(" · " + l.Compressed) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 91, Col: 57} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var11 string + templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(l.Chunks) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 94, Col: 57} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var12 string + templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(l.CompressAfter) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 95, Col: 64} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var13 string + templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(l.Retention) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 96, Col: 55} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if len(v.Tables) > 0 { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for i, t := range v.Tables { + if i > 0 { + var templ_7745c5c3_Var14 string + templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(" · ") + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 106, Col: 14} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var15 string + templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(t.Name + " " + t.Size) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 108, Col: 28} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var16 string + templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "storage.jobs")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 112, Col: 72} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "

    ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + for _, j := range v.Jobs { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + { + templ_7745c5c3_ElementWriter := templ_7745c5c3_Buffer + templ_7745c5c3_Buffer := templ.GetBuffer() + var templ_7745c5c3_ElementScripts []templ.ComponentScript + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var19 string + templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "storage.job_"+j.Name)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 118, Col: 44} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var20 string + templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(j.Relation) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 119, Col: 61} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if j.Failures > 0 { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var21 string + templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "storage.failures", "Count", j.Failures)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 121, Col: 93} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var23 string + templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(j.LastRun) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 124, Col: 101} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var25 string + templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(j.NextRun) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/storage.templ`, Line: 125, Col: 117} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "
  • ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +var _ = templruntime.GeneratedTemplate -- 2.54.1