Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

12.8 KB
Raw Blame
package store

import (
	"context"
	"path/filepath"
	"testing"
	"time"

	"github.com/rcourtman/pulse-go-rewrite/internal/recovery"
)

func TestStore_ListRollups(t *testing.T) {
	t.Parallel()

	dir := t.TempDir()
	dbPath := filepath.Join(dir, "recovery.db")

	store, err := Open(dbPath)
	if err != nil {
		t.Fatalf("Open() error = %v", err)
	}
	t.Cleanup(func() { _ = store.Close() })

	t1 := time.Date(2026, 2, 10, 10, 0, 0, 0, time.UTC)
	t2 := time.Date(2026, 2, 12, 10, 0, 0, 0, time.UTC)
	t3 := time.Date(2026, 2, 14, 10, 0, 0, 0, time.UTC)

	points := []recovery.RecoveryPoint{
		{
			ID:                "p1",
			Provider:          recovery.ProviderKubernetes,
			Kind:              recovery.KindBackup,
			Mode:              recovery.ModeRemote,
			Outcome:           recovery.OutcomeSuccess,
			StartedAt:         &t1,
			CompletedAt:       &t1,
			SubjectResourceID: "vm-1",
		},
		{
			ID:                "p2",
			Provider:          recovery.ProviderKubernetes,
			Kind:              recovery.KindBackup,
			Mode:              recovery.ModeRemote,
			Outcome:           recovery.OutcomeFailed,
			StartedAt:         &t2,
			CompletedAt:       &t2,
			SubjectResourceID: "vm-1",
		},
		{
			ID:          "p3",
			Provider:    recovery.ProviderTrueNAS,
			Kind:        recovery.KindSnapshot,
			Mode:        recovery.ModeSnapshot,
			Outcome:     recovery.OutcomeSuccess,
			StartedAt:   &t3,
			CompletedAt: &t3,
			SubjectRef: &recovery.ExternalRef{
				Type: "truenas-dataset",
				Name: "tank/apps",
				ID:   "tank/apps",
			},
		},
	}

	if err := store.UpsertPoints(context.Background(), points); err != nil {
		t.Fatalf("UpsertPoints() error = %v", err)
	}

	got, total, err := store.ListRollups(context.Background(), recovery.ListPointsOptions{Page: 1, Limit: 50})
	if err != nil {
		t.Fatalf("ListRollups() error = %v", err)
	}
	if total != 2 {
		t.Fatalf("total = %d, want 2", total)
	}
	if len(got) != 2 {
		t.Fatalf("len(rollups) = %d, want 2", len(got))
	}

	// Newest attempt first: TrueNAS dataset at t3.
	if got[0].LastAttemptAt == nil || !got[0].LastAttemptAt.Equal(t3) {
		t.Fatalf("rollup[0].LastAttemptAt = %v, want %v", got[0].LastAttemptAt, t3)
	}
	if got[0].LastOutcome != recovery.OutcomeSuccess {
		t.Fatalf("rollup[0].LastOutcome = %q, want %q", got[0].LastOutcome, recovery.OutcomeSuccess)
	}
	if got[0].RollupID == "" || got[0].RollupID == "res:vm-1" {
		t.Fatalf("rollup[0].RollupID = %q, want external key", got[0].RollupID)
	}
	if got[0].SubjectResourceID != "" {
		t.Fatalf("rollup[0].SubjectResourceID = %q, want empty for external subject", got[0].SubjectResourceID)
	}
	if got[0].SubjectRef == nil || got[0].SubjectRef.Type != "truenas-dataset" || got[0].SubjectRef.Name != "tank/apps" {
		t.Fatalf("rollup[0].SubjectRef = %#v, want truenas dataset ref", got[0].SubjectRef)
	}
	if got[0].Display == nil || got[0].Display.SubjectLabel != "tank/apps" {
		t.Fatalf("rollup[0].Display = %#v, want subject label tank/apps", got[0].Display)
	}
	if got[0].Display == nil || got[0].Display.ItemType != "dataset" {
		t.Fatalf("rollup[0].Display = %#v, want item type dataset", got[0].Display)
	}

	// Second: vm-1 with latest failure at t2 and last success at t1.
	if got[1].RollupID != "res:vm-1" {
		t.Fatalf("rollup[1].RollupID = %q, want %q", got[1].RollupID, "res:vm-1")
	}
	if got[1].SubjectResourceID != "vm-1" {
		t.Fatalf("rollup[1].SubjectResourceID = %q, want %q", got[1].SubjectResourceID, "vm-1")
	}
	if got[1].SubjectRef != nil {
		t.Fatalf("rollup[1].SubjectRef = %#v, want nil", got[1].SubjectRef)
	}
	if got[1].Display == nil || got[1].Display.SubjectLabel != "vm-1" {
		t.Fatalf("rollup[1].Display = %#v, want subject label vm-1", got[1].Display)
	}
	if got[1].Display == nil || got[1].Display.ItemType != "" {
		t.Fatalf("rollup[1].Display = %#v, want empty item type when subject type is unknown", got[1].Display)
	}
	if got[1].LastAttemptAt == nil || !got[1].LastAttemptAt.Equal(t2) {
		t.Fatalf("rollup[1].LastAttemptAt = %v, want %v", got[1].LastAttemptAt, t2)
	}
	if got[1].LastSuccessAt == nil || !got[1].LastSuccessAt.Equal(t1) {
		t.Fatalf("rollup[1].LastSuccessAt = %v, want %v", got[1].LastSuccessAt, t1)
	}
	if got[1].LastOutcome != recovery.OutcomeFailed {
		t.Fatalf("rollup[1].LastOutcome = %q, want %q", got[1].LastOutcome, recovery.OutcomeFailed)
	}

	// Smoke: From filter excludes older entries.
	from := t3.Add(-1 * time.Minute)
	got2, total2, err := store.ListRollups(context.Background(), recovery.ListPointsOptions{From: &from, Page: 1, Limit: 50})
	if err != nil {
		t.Fatalf("ListRollups(from) error = %v", err)
	}
	if total2 != 1 || len(got2) != 1 {
		t.Fatalf("ListRollups(from) total=%d len=%d, want 1/1", total2, len(got2))
	}

	verified := true
	unverified := false
	if err := store.UpsertPoints(context.Background(), []recovery.RecoveryPoint{
		{
			ID:                "p4",
			Provider:          recovery.ProviderKubernetes,
			Kind:              recovery.KindBackup,
			Mode:              recovery.ModeRemote,
			Outcome:           recovery.OutcomeSuccess,
			StartedAt:         &t3,
			CompletedAt:       &t3,
			Verified:          &verified,
			SubjectResourceID: "pod-1",
			SubjectRef: &recovery.ExternalRef{
				Type:      "pod",
				Name:      "pod-1",
				Namespace: "default",
				ID:        "pod-1",
			},
			RepositoryRef: &recovery.ExternalRef{
				Type: "velero-backup-storage-location",
				Name: "repo-a",
			},
			Details: map[string]any{
				"k8sClusterName": "prod-cluster",
				"node":           "worker-1",
			},
		},
		{
			ID:                "p5",
			Provider:          recovery.ProviderKubernetes,
			Kind:              recovery.KindBackup,
			Mode:              recovery.ModeRemote,
			Outcome:           recovery.OutcomeFailed,
			StartedAt:         &t3,
			CompletedAt:       &t3,
			Verified:          &unverified,
			SubjectResourceID: "pod-2",
			SubjectRef: &recovery.ExternalRef{
				Type:      "pod",
				Name:      "pod-2",
				Namespace: "kube-system",
				ID:        "pod-2",
			},
			Details: map[string]any{
				"k8sClusterName": "other-cluster",
				"node":           "worker-2",
			},
		},
	}); err != nil {
		t.Fatalf("UpsertPoints(extra) error = %v", err)
	}

	got3, total3, err := store.ListRollups(context.Background(), recovery.ListPointsOptions{
		Page:           1,
		Limit:          50,
		ClusterLabel:   "prod-cluster",
		NodeHostLabel:  "worker-1",
		NamespaceLabel: "default",
		Verification:   "verified",
		WorkloadOnly:   true,
		Query:          "repo-a",
	})
	if err != nil {
		t.Fatalf("ListRollups(normalized filters) error = %v", err)
	}
	if total3 != 1 || len(got3) != 1 {
		t.Fatalf("ListRollups(normalized filters) total=%d len=%d, want 1/1", total3, len(got3))
	}
	if got3[0].RollupID != "res:pod-1" {
		t.Fatalf("rollup with normalized filters = %q, want %q", got3[0].RollupID, "res:pod-1")
	}
	if got3[0].Display == nil || got3[0].Display.SubjectLabel != "default/pod-1" {
		t.Fatalf("rollup with normalized filters display = %#v, want subject label default/pod-1", got3[0].Display)
	}
	if got3[0].Display == nil || got3[0].Display.ItemType != "pod" {
		t.Fatalf("rollup with normalized filters display = %#v, want item type pod", got3[0].Display)
	}

	got4, total4, err := store.ListRollups(context.Background(), recovery.ListPointsOptions{
		Page:     1,
		Limit:    50,
		ItemType: "dataset",
	})
	if err != nil {
		t.Fatalf("ListRollups(itemType) error = %v", err)
	}
	if total4 != 1 || len(got4) != 1 || got4[0].RollupID == "res:vm-1" {
		t.Fatalf("ListRollups(itemType) = %#v total=%d, want only dataset rollup", got4, total4)
	}
}

func TestStore_ListRollups_VerifyIntent(t *testing.T) {
	t.Parallel()

	dir := t.TempDir()
	dbPath := filepath.Join(dir, "recovery.db")

	store, err := Open(dbPath)
	if err != nil {
		t.Fatalf("Open() error = %v", err)
	}
	t.Cleanup(func() { _ = store.Close() })

	// Truncate to millisecond precision: the persistence layer stores
	// completion timestamps as int64 milliseconds, so any sub-millisecond
	// precision in time.Now() would not round-trip and would fail the
	// reflective Equal() assertion below.
	now := time.Now().UTC().Truncate(time.Millisecond)
	recent := now.Add(-2 * 24 * time.Hour)
	old := now.Add(-21 * 24 * time.Hour)

	verified := true
	unverified := false

	points := []recovery.RecoveryPoint{
		{
			ID:                "verified-fresh",
			Provider:          recovery.ProviderProxmoxPBS,
			Kind:              recovery.KindBackup,
			Mode:              recovery.ModeRemote,
			Outcome:           recovery.OutcomeSuccess,
			StartedAt:         &recent,
			CompletedAt:       &recent,
			Verified:          &verified,
			SubjectResourceID: "vm-verified",
		},
		{
			ID:                "stale-fresh-success",
			Provider:          recovery.ProviderProxmoxPBS,
			Kind:              recovery.KindBackup,
			Mode:              recovery.ModeRemote,
			Outcome:           recovery.OutcomeSuccess,
			StartedAt:         &recent,
			CompletedAt:       &recent,
			Verified:          &unverified,
			SubjectResourceID: "vm-stale",
		},
		{
			ID:                "stale-old-verification",
			Provider:          recovery.ProviderProxmoxPBS,
			Kind:              recovery.KindBackup,
			Mode:              recovery.ModeRemote,
			Outcome:           recovery.OutcomeSuccess,
			StartedAt:         &old,
			CompletedAt:       &old,
			Verified:          &verified,
			SubjectResourceID: "vm-stale",
		},
		{
			ID:                "unknown-failed-only",
			Provider:          recovery.ProviderProxmoxPBS,
			Kind:              recovery.KindBackup,
			Mode:              recovery.ModeRemote,
			Outcome:           recovery.OutcomeFailed,
			StartedAt:         &recent,
			CompletedAt:       &recent,
			SubjectResourceID: "vm-unknown",
		},
	}

	if err := store.UpsertPoints(context.Background(), points); err != nil {
		t.Fatalf("UpsertPoints() error = %v", err)
	}

	got, _, err := store.ListRollups(context.Background(), recovery.ListPointsOptions{Page: 1, Limit: 50})
	if err != nil {
		t.Fatalf("ListRollups() error = %v", err)
	}

	intentByRollup := make(map[string]recovery.VerifyIntent, len(got))
	verifiedAtByRollup := make(map[string]*time.Time, len(got))
	for _, r := range got {
		intentByRollup[r.RollupID] = r.VerifyIntent
		verifiedAtByRollup[r.RollupID] = r.LastVerifiedAt
	}

	if intentByRollup["res:vm-verified"] != recovery.VerifyIntentVerified {
		t.Fatalf("vm-verified intent = %q, want %q",
			intentByRollup["res:vm-verified"], recovery.VerifyIntentVerified)
	}
	if intentByRollup["res:vm-stale"] != recovery.VerifyIntentStale {
		t.Fatalf("vm-stale intent = %q, want %q",
			intentByRollup["res:vm-stale"], recovery.VerifyIntentStale)
	}
	if intentByRollup["res:vm-unknown"] != recovery.VerifyIntentUnknown {
		t.Fatalf("vm-unknown intent = %q, want %q",
			intentByRollup["res:vm-unknown"], recovery.VerifyIntentUnknown)
	}

	if got := verifiedAtByRollup["res:vm-verified"]; got == nil || !got.Equal(recent) {
		t.Fatalf("vm-verified lastVerifiedAt = %v, want %v", got, recent)
	}
	if got := verifiedAtByRollup["res:vm-stale"]; got == nil || !got.Equal(old) {
		t.Fatalf("vm-stale lastVerifiedAt = %v, want historical %v", got, old)
	}
	if got := verifiedAtByRollup["res:vm-unknown"]; got != nil {
		t.Fatalf("vm-unknown lastVerifiedAt = %v, want nil", got)
	}
}

func TestStore_ListRollups_IgnoresMalformedSubjectRefJSON(t *testing.T) {
	t.Parallel()

	dir := t.TempDir()
	dbPath := filepath.Join(dir, "recovery.db")

	store, err := Open(dbPath)
	if err != nil {
		t.Fatalf("Open() error = %v", err)
	}
	t.Cleanup(func() { _ = store.Close() })

	now := time.Date(2026, 2, 19, 12, 0, 0, 0, time.UTC)

	point := recovery.RecoveryPoint{
		ID:          "rollup-bad-json",
		Provider:    recovery.ProviderTrueNAS,
		Kind:        recovery.KindSnapshot,
		Mode:        recovery.ModeSnapshot,
		Outcome:     recovery.OutcomeSuccess,
		StartedAt:   &now,
		CompletedAt: &now,
		SubjectRef: &recovery.ExternalRef{
			Type: "truenas-dataset",
			Name: "tank/apps",
			ID:   "tank/apps",
		},
	}

	if err := store.UpsertPoints(context.Background(), []recovery.RecoveryPoint{point}); err != nil {
		t.Fatalf("UpsertPoints() error = %v", err)
	}

	if _, err := store.db.ExecContext(
		context.Background(),
		`UPDATE recovery_points
		 SET subject_ref_json = '{'
		 WHERE id = ?`,
		point.ID,
	); err != nil {
		t.Fatalf("corrupt recovery rollup json: %v", err)
	}

	got, total, err := store.ListRollups(context.Background(), recovery.ListPointsOptions{Page: 1, Limit: 50})
	if err != nil {
		t.Fatalf("ListRollups() error = %v, want graceful degradation", err)
	}
	if total != 1 || len(got) != 1 {
		t.Fatalf("ListRollups() total=%d len=%d, want 1/1", total, len(got))
	}
	if got[0].SubjectRef != nil {
		t.Fatalf("SubjectRef = %#v, want nil after malformed json fallback", got[0].SubjectRef)
	}
	if got[0].Display == nil || got[0].Display.SubjectLabel != "tank/apps" {
		t.Fatalf("Display = %#v, want preserved normalized subject label", got[0].Display)
	}
	if got[0].Display == nil || got[0].Display.ItemType != "dataset" {
		t.Fatalf("Display = %#v, want preserved normalized item type", got[0].Display)
	}
}