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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Canonicalize reporting handler contract
rcourtman3a7a39996deb
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 26dafc3e38..70b0e35171 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -181,6 +181,11 @@ plus a VM inventory definition route that own panel copy, performance reportoptions, export title, column schema, and filename prefixes. Lifecycle-adjacent install and fleet surfaces may read those facts, but they must notredefine reporting or inventory schema locally.+That same API-owned performance-report definition also governs transport-side+validation and attachment naming. Lifecycle-adjacent fleet surfaces may depend+on those downloads, but they must treat allowed formats, multi-resource caps,+optional metric/title support, and filename prefixes as API-owned reporting+contract rather than mirroring local constants.That adjacent export contract now also carries canonical Proxmox poolmembership for each VM row. Lifecycle-adjacent install and fleet surfaces mayreuse those current-state facts, but they must still treat the pool column asdiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 605e45cd38..5dc3e6e165 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -231,6 +231,11 @@ That same catalog payload also owns the optional performance-report capabilitysurface: `supportsMetricFilter` and `supportsCustomTitle` are contract flags,not UI hints, so frontend consumers and request builders must not render oremit unsupported metric-filter or custom-title fields from local assumptions.+The same performance-report catalog definition also owns backend transport+validation and download semantics. `internal/api/metrics_reporting_handlers.go`+must derive allowed formats, default format selection, multi-resource limits,+optional metric/title field emission, and attachment filename prefixes from the+canonical reporting definition instead of hardcoding a second local contract.The `/api/resources` serializer now also refreshes canonical identity andpolicy metadata through the shared unified-resource helper before it writesthe payload, so backend and frontend contract tests stay aligned on onediff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 2ac729472a..8d6648c719 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -227,6 +227,11 @@ plus a VM inventory definition route that own panel copy, stable columnschema, and filename prefix. Storage and recovery flows may read those factswhen they need fleet context, but they must not fork their own reporting orinventory column contract.+That same API-owned performance-report definition also governs transport-side+validation and attachment naming. Storage and recovery flows may consume those+downloads, but they must treat allowed formats, multi-resource caps, optional+metric/title support, and filename prefixes as API/reporting contract rather+than rebuilding local reporting constants.That adjacent export contract now also includes canonical Proxmox poolmembership for each VM row. Storage and recovery flows may use those current-state facts when they need fleet context, but they must consume the API-owneddiff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 67de48c3cc..012b5c397c 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -31,6 +31,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/updates"authpkg "github.com/rcourtman/pulse-go-rewrite/pkg/auth"pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"+ "github.com/rcourtman/pulse-go-rewrite/pkg/reporting")func TestContract_FindingJSONSnapshot(t *testing.T) {@@ -466,6 +467,37 @@ func TestContract_ReportingCatalogJSONSnapshot(t *testing.T) {assertJSONSnapshot(t, rec.Body.Bytes(), want)}+func TestContract_PerformanceReportTransportUsesCatalogDefinition(t *testing.T) {+ engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}+ original := reporting.GetEngine()+ reporting.SetEngine(engine)+ t.Cleanup(func() { reporting.SetEngine(original) })++ handler := NewReportingHandlers(nil, nil)+ req := httptest.NewRequest(+ http.MethodGet,+ "/api/reporting?resourceType=node&resourceId=node-1&metricType=+cpu+&title=+Node+report+",+ nil,+ )+ rec := httptest.NewRecorder()++ handler.HandleGenerateReport(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", rec.Code, rec.Body.String())+ }+ definition := reporting.DescribePerformanceReport()+ if got := rec.Header().Get("Content-Disposition"); !strings.HasPrefix(got, fmt.Sprintf("attachment; filename=\"%s-node-1-", definition.SingleFilenamePrefix)) {+ t.Fatalf("expected canonical performance-report attachment filename, got %q", got)+ }+ if engine.lastReq.Format != definition.DefaultFormat {+ t.Fatalf("expected default format %q, got %q", definition.DefaultFormat, engine.lastReq.Format)+ }+ if engine.lastReq.MetricType != "cpu" || engine.lastReq.Title != "Node report" {+ t.Fatalf("expected trimmed canonical optional fields, got %+v", engine.lastReq)+ }+}+func TestContract_VMInventoryExportDefinitionJSONSnapshot(t *testing.T) {handler := NewReportingHandlers(nil, nil)req := httptest.NewRequest(http.MethodGet, "/api/admin/reports/inventory/vms/definition", nil)diff --git a/internal/api/metrics_reporting_handlers.go b/internal/api/metrics_reporting_handlers.goindex 354084cb11..50cc8a36a1 100644--- a/internal/api/metrics_reporting_handlers.go+++ b/internal/api/metrics_reporting_handlers.go@@ -42,6 +42,39 @@ type ReportingHandlers struct {recoveryManager *recoverymanager.Manager}+func performanceReportDefinition() reporting.PerformanceReportDefinition {+ return reporting.DescribePerformanceReport()+}++func normalizePerformanceReportFormat(raw string, definition reporting.PerformanceReportDefinition) (reporting.ReportFormat, error) {+ format := reporting.ReportFormat(strings.TrimSpace(raw))+ if format == "" {+ format = definition.DefaultFormat+ }+ if !definition.SupportsFormat(format) {+ return "", fmt.Errorf("Format must be 'pdf' or 'csv'")+ }+ return format, nil+}++func normalizePerformanceReportOptionalFields(+ definition reporting.PerformanceReportDefinition,+ metricType string,+ title string,+) (string, string) {+ normalizedMetricType := strings.TrimSpace(metricType)+ normalizedTitle := strings.TrimSpace(title)++ if !definition.SupportsMetricFilter {+ normalizedMetricType = ""+ }+ if !definition.SupportsCustomTitle {+ normalizedTitle = ""+ }++ return normalizedMetricType, normalizedTitle+}+type reportingEnrichmentSnapshot struct {Nodes []models.NodeVMs []models.VM@@ -257,15 +290,11 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.return}+ definition := performanceReportDefinition()q := r.URL.Query()- format := reporting.ReportFormat(q.Get("format"))- if format == "" {- format = reporting.FormatPDF- }-- // Validate format is one of known values- if format != reporting.FormatPDF && format != reporting.FormatCSV {- writeErrorResponse(w, http.StatusBadRequest, "invalid_format", "Format must be 'pdf' or 'csv'", nil)+ format, err := normalizePerformanceReportFormat(q.Get("format"), definition)+ if err != nil {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_format", err.Error(), nil)return}@@ -291,7 +320,11 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.return}- metricType := q.Get("metricType")+ metricType, title := normalizePerformanceReportOptionalFields(+ definition,+ q.Get("metricType"),+ q.Get("title"),+ )// Parse rangeend := time.Now()@@ -315,7 +348,7 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.Start: start,End: end,Format: format,- Title: q.Get("title"),+ Title: title,}// Enrich with resource data if monitor is available@@ -333,7 +366,7 @@ func (h *ReportingHandlers) HandleGenerateReport(w http.ResponseWriter, r *http.w.Header().Set("Content-Type", contentType)// Build safe filename - sanitize resourceID to prevent header injectionsafeResourceID := sanitizeFilename(resourceID)- filename := fmt.Sprintf("report-%s-%s.%s", safeResourceID, time.Now().Format("20060102"), format)+ filename := fmt.Sprintf("%s-%s-%s.%s", definition.SingleFilenamePrefix, safeResourceID, time.Now().Format("20060102"), format)w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))w.Write(data)}@@ -614,6 +647,7 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *return}+ definition := performanceReportDefinition()var body multiReportRequestBodyif err := json.NewDecoder(r.Body).Decode(&body); err != nil {writeErrorResponse(w, http.StatusBadRequest, "invalid_body", "Invalid request body", nil)@@ -625,20 +659,17 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *writeErrorResponse(w, http.StatusBadRequest, "no_resources", "At least one resource is required", nil)return}- if len(body.Resources) > 50 {- writeErrorResponse(w, http.StatusBadRequest, "too_many_resources", "Maximum 50 resources allowed", nil)+ if len(body.Resources) > definition.MultiResourceMax {+ writeErrorResponse(w, http.StatusBadRequest, "too_many_resources", fmt.Sprintf("Maximum %d resources allowed", definition.MultiResourceMax), nil)return}- // Validate format- format := reporting.ReportFormat(body.Format)- if format == "" {- format = reporting.FormatPDF- }- if format != reporting.FormatPDF && format != reporting.FormatCSV {- writeErrorResponse(w, http.StatusBadRequest, "invalid_format", "Format must be 'pdf' or 'csv'", nil)+ format, err := normalizePerformanceReportFormat(body.Format, definition)+ if err != nil {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_format", err.Error(), nil)return}+ metricType, title := normalizePerformanceReportOptionalFields(definition, body.MetricType, body.Title)// Parse time rangeend := time.Now()@@ -659,8 +690,8 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *Format: format,Start: start,End: end,- Title: body.Title,- MetricType: body.MetricType,+ Title: title,+ MetricType: metricType,}// Get monitor state for enrichment@@ -686,11 +717,11 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *req := reporting.MetricReportRequest{ResourceType: resourceType,ResourceID: res.ResourceID,- MetricType: body.MetricType,+ MetricType: metricType,Start: start,End: end,Format: format,- Title: body.Title,+ Title: title,}// Enrich with resource data@@ -708,7 +739,7 @@ func (h *ReportingHandlers) HandleGenerateMultiReport(w http.ResponseWriter, r *}w.Header().Set("Content-Type", contentType)- filename := fmt.Sprintf("fleet-report-%s.%s", time.Now().Format("20060102"), format)+ filename := fmt.Sprintf("%s-%s.%s", definition.MultiFilenamePrefix, time.Now().Format("20060102"), format)w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))w.Write(data)}diff --git a/internal/api/reporting_handlers_test.go b/internal/api/reporting_handlers_test.goindex c3286f1fa9..0135f7c8ad 100644--- a/internal/api/reporting_handlers_test.go+++ b/internal/api/reporting_handlers_test.go@@ -2,6 +2,7 @@ package apiimport ("encoding/json"+ "fmt""net/http""net/http/httptest""net/url"@@ -126,8 +127,9 @@ func TestReportingHandlers_GenerateReport(t *testing.T) {if ct := rr.Header().Get("Content-Type"); ct != "application/pdf" {t.Fatalf("expected content-type application/pdf, got %q", ct)}- if disp := rr.Header().Get("Content-Disposition"); !strings.Contains(disp, "report-node-1") {- t.Fatalf("expected content-disposition to contain sanitized filename, got %q", disp)+ definition := reporting.DescribePerformanceReport()+ if disp := rr.Header().Get("Content-Disposition"); !strings.Contains(disp, definition.SingleFilenamePrefix+"-node-1") {+ t.Fatalf("expected content-disposition to contain canonical filename prefix, got %q", disp)}if body := rr.Body.String(); body != "report" {t.Fatalf("expected report body, got %q", body)@@ -138,6 +140,33 @@ func TestReportingHandlers_GenerateReport(t *testing.T) {}}+func TestReportingHandlers_GenerateReport_TrimsOptionalFields(t *testing.T) {+ engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}+ original := reporting.GetEngine()+ reporting.SetEngine(engine)+ t.Cleanup(func() { reporting.SetEngine(original) })++ handler := NewReportingHandlers(nil, nil)+ req := httptest.NewRequest(+ http.MethodGet,+ "/api/reporting?format=pdf&resourceType=node&resourceId=node-1&metricType=+cpu+&title=+Node+report+",+ nil,+ )+ rr := httptest.NewRecorder()++ handler.HandleGenerateReport(rr, req)++ if rr.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d body=%s", http.StatusOK, rr.Code, rr.Body.String())+ }+ if engine.lastReq.MetricType != "cpu" {+ t.Fatalf("expected trimmed metric type, got %q", engine.lastReq.MetricType)+ }+ if engine.lastReq.Title != "Node report" {+ t.Fatalf("expected trimmed title, got %q", engine.lastReq.Title)+ }+}+func TestReportingHandlers_GenerateReport_RejectsLegacyResourceTypeAlias(t *testing.T) {engine := &stubReportingEngine{data: []byte("report"), contentType: "application/pdf"}original := reporting.GetEngine()@@ -328,6 +357,66 @@ func TestReportingHandlers_ExportVMInventory_InvalidFormat(t *testing.T) {}}+func TestReportingHandlers_GenerateMultiReport_UsesCatalogLimit(t *testing.T) {+ engine := &stubReportingEngine{data: []byte("report"), contentType: "text/csv"}+ original := reporting.GetEngine()+ reporting.SetEngine(engine)+ t.Cleanup(func() { reporting.SetEngine(original) })++ handler := NewReportingHandlers(nil, nil)+ definition := reporting.DescribePerformanceReport()+ resources := make([]string, 0, definition.MultiResourceMax+1)+ for i := 0; i < definition.MultiResourceMax+1; i++ {+ resources = append(resources, fmt.Sprintf(`{"resourceType":"vm","resourceId":"vm-%d"}`, i))+ }+ body := `{"resources":[` + strings.Join(resources, ",") + `],"format":"csv"}`+ req := httptest.NewRequest(http.MethodPost, "/api/reporting/generate-multi", strings.NewReader(body))+ rr := httptest.NewRecorder()++ handler.HandleGenerateMultiReport(rr, req)++ if rr.Code != http.StatusBadRequest {+ t.Fatalf("expected status %d, got %d body=%s", http.StatusBadRequest, rr.Code, rr.Body.String())+ }+ if !strings.Contains(rr.Body.String(), fmt.Sprintf("Maximum %d resources allowed", definition.MultiResourceMax)) {+ t.Fatalf("expected canonical multi-resource max in error, got %s", rr.Body.String())+ }+}++func TestReportingHandlers_GenerateMultiReport_TrimsOptionalFieldsAndUsesCanonicalFilename(t *testing.T) {+ engine := &stubReportingEngine{data: []byte("report"), contentType: "text/csv"}+ original := reporting.GetEngine()+ reporting.SetEngine(engine)+ t.Cleanup(func() { reporting.SetEngine(original) })++ handler := NewReportingHandlers(nil, nil)+ body := `{"resources":[{"resourceType":"vm","resourceId":"vm-1"}],"format":"csv","metricType":" cpu ","title":" Fleet report "}`+ req := httptest.NewRequest(http.MethodPost, "/api/reporting/generate-multi", strings.NewReader(body))+ rr := httptest.NewRecorder()++ handler.HandleGenerateMultiReport(rr, req)++ if rr.Code != http.StatusOK {+ t.Fatalf("expected status %d, got %d body=%s", http.StatusOK, rr.Code, rr.Body.String())+ }+ definition := reporting.DescribePerformanceReport()+ if disp := rr.Header().Get("Content-Disposition"); !strings.Contains(disp, definition.MultiFilenamePrefix+"-") {+ t.Fatalf("expected canonical multi-report filename prefix, got %q", disp)+ }+ if engine.lastMulti.MetricType != "cpu" {+ t.Fatalf("expected trimmed metric type, got %q", engine.lastMulti.MetricType)+ }+ if engine.lastMulti.Title != "Fleet report" {+ t.Fatalf("expected trimmed title, got %q", engine.lastMulti.Title)+ }+ if len(engine.lastMulti.Resources) != 1 {+ t.Fatalf("expected one resource request, got %+v", engine.lastMulti.Resources)+ }+ if engine.lastMulti.Resources[0].MetricType != "cpu" || engine.lastMulti.Resources[0].Title != "Fleet report" {+ t.Fatalf("expected canonical optional fields to propagate to per-resource requests, got %+v", engine.lastMulti.Resources[0])+ }+}+func TestReportingHandlers_ExportVMInventory_EmptySnapshotStillReturnsCSVHeader(t *testing.T) {handler := NewReportingHandlers(nil, nil)req := httptest.NewRequest(http.MethodGet, "/api/admin/reports/inventory/vms/export", nil)diff --git a/pkg/reporting/catalog.go b/pkg/reporting/catalog.goindex cd192fa4c2..e1a3e63812 100644--- a/pkg/reporting/catalog.go+++ b/pkg/reporting/catalog.go@@ -45,6 +45,17 @@ type ReportingCatalog struct {VMInventoryExport VMInventoryExportDefinition `json:"vmInventoryExport"`}+// SupportsFormat reports whether the performance reporting surface allows the+// given output format.+func (d PerformanceReportDefinition) SupportsFormat(format ReportFormat) bool {+ for _, candidate := range d.Formats {+ if candidate.Value == format {+ return true+ }+ }+ return false+}+// DescribePerformanceReport returns the canonical definition for Pulse's// historical performance reporting surface.func DescribePerformanceReport() PerformanceReportDefinition {diff --git a/pkg/reporting/catalog_test.go b/pkg/reporting/catalog_test.goindex 8289909ad4..5508704fab 100644--- a/pkg/reporting/catalog_test.go+++ b/pkg/reporting/catalog_test.go@@ -21,3 +21,17 @@ func TestDescribeReportingCatalog_DefinesCanonicalSurfaces(t *testing.T) {t.Fatalf("vm inventory export endpoint = %q", catalog.VMInventoryExport.ExportEndpoint)}}++func TestPerformanceReportDefinition_SupportsFormat(t *testing.T) {+ definition := DescribePerformanceReport()++ if !definition.SupportsFormat(FormatPDF) {+ t.Fatalf("expected PDF to be supported")+ }+ if !definition.SupportsFormat(FormatCSV) {+ t.Fatalf("expected CSV to be supported")+ }+ if definition.SupportsFormat(ReportFormat("xlsx")) {+ t.Fatalf("did not expect xlsx to be supported")+ }+}