Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: replicate perses structs but with proper plugin references (#11031)

Naman Verma89d394145dcb
diff --git a/pkg/types/dashboardtypes/dashboard_v2.go b/pkg/types/dashboardtypes/dashboard_v2.go
deleted file mode 100644
index 1839b21665..0000000000
--- a/pkg/types/dashboardtypes/dashboard_v2.go
+++ /dev/null
@@ -1,262 +0,0 @@
-package dashboardtypes
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "slices"
- "strings"
-
- "github.com/SigNoz/signoz/pkg/errors"
- qb "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
- "github.com/go-playground/validator/v10"
- v1 "github.com/perses/perses/pkg/model/api/v1"
- "github.com/perses/perses/pkg/model/api/v1/common"
- "github.com/perses/perses/pkg/model/api/v1/dashboard"
-)
-
-// StorableDashboardDataV2 wraps v1.DashboardSpec (Perses) with additional SigNoz-specific fields.
-//
-// We embed DashboardSpec (not v1.Dashboard) to avoid carrying Perses's Metadata
-// (Name, Project, CreatedAt, UpdatedAt, Tags, Version) and Kind field. SigNoz
-// manages identity (ID), timestamps (TimeAuditable), and multi-tenancy (OrgID)
-// separately on StorableDashboardV2/DashboardV2.
-//
-// The following v1 request fields map to locations inside v1.DashboardSpec:
-// - title → Display.Name (common.Display)
-// - description → Display.Description (common.Display)
-//
-// Fields that have no Perses equivalent will be added in this wrapper (like image, uploadGrafana, etc.)
-type StorableDashboardDataV2 = v1.DashboardSpec
-
-// UnmarshalAndValidateDashboardV2JSON unmarshals the JSON into a StorableDashboardDataV2
-// (= PostableDashboardV2 = UpdatableDashboardV2) and validates plugin kinds and specs.
-func UnmarshalAndValidateDashboardV2JSON(data []byte) (*StorableDashboardDataV2, error) {
- var d StorableDashboardDataV2
- // Note: DashboardSpec has a custom UnmarshalJSON which prevents
- // DisallowUnknownFields from working at the top level. Unknown
- // fields in plugin specs are still rejected by validateAndNormalizePluginSpec.
- if err := json.Unmarshal(data, &d); err != nil {
- return nil, err
- }
- if err := validateDashboardV2(d); err != nil {
- return nil, err
- }
- return &d, nil
-}
-
-// Plugin kind → spec type factory. Each value is a pointer to the zero value of the
-// expected spec struct. validatePluginSpec marshals plugin.Spec back to JSON and
-// unmarshals into the typed struct to catch field-level errors.
-var (
- panelPluginSpecs = map[PanelPluginKind]func() any{
- PanelKindTimeSeries: func() any { return new(TimeSeriesPanelSpec) },
- PanelKindBarChart: func() any { return new(BarChartPanelSpec) },
- PanelKindNumber: func() any { return new(NumberPanelSpec) },
- PanelKindPieChart: func() any { return new(PieChartPanelSpec) },
- PanelKindTable: func() any { return new(TablePanelSpec) },
- PanelKindHistogram: func() any { return new(HistogramPanelSpec) },
- PanelKindList: func() any { return new(ListPanelSpec) },
- }
- queryPluginSpecs = map[QueryPluginKind]func() any{
- QueryKindBuilder: func() any { return new(BuilderQuerySpec) },
- QueryKindComposite: func() any { return new(CompositeQuerySpec) },
- QueryKindFormula: func() any { return new(FormulaSpec) },
- QueryKindPromQL: func() any { return new(PromQLQuerySpec) },
- QueryKindClickHouseSQL: func() any { return new(ClickHouseSQLQuerySpec) },
- QueryKindTraceOperator: func() any { return new(TraceOperatorSpec) },
- }
- variablePluginSpecs = map[VariablePluginKind]func() any{
- VariableKindDynamic: func() any { return new(DynamicVariableSpec) },
- VariableKindQuery: func() any { return new(QueryVariableSpec) },
- VariableKindCustom: func() any { return new(CustomVariableSpec) },
- VariableKindTextbox: func() any { return new(TextboxVariableSpec) },
- }
- datasourcePluginSpecs = map[DatasourcePluginKind]func() any{
- DatasourceKindSigNoz: func() any { return new(struct{}) },
- }
-
- // allowedQueryKinds maps each panel plugin kind to the query plugin
- // kinds it supports. Composite sub-query types are mapped to these
- // same kind strings via compositeSubQueryTypeToPluginKind.
- allowedQueryKinds = map[PanelPluginKind][]QueryPluginKind{
- PanelKindTimeSeries: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
- PanelKindBarChart: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
- PanelKindNumber: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
- PanelKindHistogram: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
- PanelKindPieChart: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
- PanelKindTable: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
- PanelKindList: {QueryKindBuilder},
- }
-
- // compositeSubQueryTypeToPluginKind maps CompositeQuery sub-query type
- // strings to the equivalent top-level query plugin kind for validation.
- compositeSubQueryTypeToPluginKind = map[qb.QueryType]QueryPluginKind{
- qb.QueryTypeBuilder: QueryKindBuilder,
- qb.QueryTypeFormula: QueryKindFormula,
- qb.QueryTypeTraceOperator: QueryKindTraceOperator,
- qb.QueryTypePromQL: QueryKindPromQL,
- qb.QueryTypeClickHouseSQL: QueryKindClickHouseSQL,
- }
-)
-
-func validateDashboardV2(d StorableDashboardDataV2) error {
- for name, ds := range d.Datasources {
- if err := validateDatasourcePlugin(&ds.Plugin, fmt.Sprintf("spec.datasources.%s.plugin", name)); err != nil {
- return err
- }
- }
-
- for i, v := range d.Variables {
- if err := validateVariablePlugin(v, fmt.Sprintf("spec.variables[%d]", i)); err != nil {
- return err
- }
- }
-
- for key, panel := range d.Panels {
- if panel == nil {
- return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.panels.%s: panel must not be null", key)
- }
- path := fmt.Sprintf("spec.panels.%s", key)
- if err := validatePanelPlugin(&panel.Spec.Plugin, path+".spec.plugin"); err != nil {
- return err
- }
- panelKind := PanelPluginKind(panel.Spec.Plugin.Kind)
- allowed := allowedQueryKinds[panelKind]
- for qi := range panel.Spec.Queries {
- queryPath := fmt.Sprintf("%s.spec.queries[%d].spec.plugin", path, qi)
- if err := validateQueryPlugin(&panel.Spec.Queries[qi].Spec.Plugin, queryPath); err != nil {
- return err
- }
- if err := validateQueryAllowedForPanel(panel.Spec.Queries[qi].Spec.Plugin, allowed, panelKind, queryPath); err != nil {
- return err
- }
- }
- }
-
- return nil
-}
-
-func validateDatasourcePlugin(plugin *common.Plugin, path string) error {
- kind := DatasourcePluginKind(plugin.Kind)
- factory, ok := datasourcePluginSpecs[kind]
- if !ok {
- return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput,
- "%s: unknown datasource plugin kind %q; allowed values: %s", path, kind, formatEnum(kind.Enum()))
- }
- return validateAndNormalizePluginSpec(plugin, factory, path)
-}
-
-func validateVariablePlugin(v dashboard.Variable, path string) error {
- switch spec := v.Spec.(type) {
- case *dashboard.ListVariableSpec:
- pluginPath := path + ".spec.plugin"
- kind := VariablePluginKind(spec.Plugin.Kind)
- factory, ok := variablePluginSpecs[kind]
- if !ok {
- return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput,
- "%s: unknown variable plugin kind %q; allowed values: %s", pluginPath, kind, formatEnum(kind.Enum()))
- }
- return validateAndNormalizePluginSpec(&spec.Plugin, factory, pluginPath)
- case *dashboard.TextVariableSpec:
- // TextVariables have no plugin, nothing to validate.
- return nil
- default:
- return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "%s: unsupported variable kind %q", path, v.Kind)
- }
-}
-
-func validatePanelPlugin(plugin *common.Plugin, path string) error {
- kind := PanelPluginKind(plugin.Kind)
- factory, ok := panelPluginSpecs[kind]
- if !ok {
- return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput,
- "%s: unknown panel plugin kind %q; allowed values: %s", path, kind, formatEnum(kind.Enum()))
- }
- return validateAndNormalizePluginSpec(plugin, factory, path)
-}
-
-func validateQueryPlugin(plugin *common.Plugin, path string) error {
- kind := QueryPluginKind(plugin.Kind)
- factory, ok := queryPluginSpecs[kind]
- if !ok {
- return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput,
- "%s: unknown query plugin kind %q; allowed values: %s", path, kind, formatEnum(kind.Enum()))
- }
- return validateAndNormalizePluginSpec(plugin, factory, path)
-}
-
-func formatEnum(values []any) string {
- parts := make([]string, len(values))
- for i, v := range values {
- parts[i] = fmt.Sprintf("`%v`", v)
- }
- return strings.Join(parts, ", ")
-}
-
-// validateAndNormalizePluginSpec validates the plugin spec and writes the typed
-// struct (with defaults) back into plugin.Spec so that DB storage and API
-// responses contain normalized values.
-func validateAndNormalizePluginSpec(plugin *common.Plugin, factory func() any, path string) error {
- if plugin.Kind == "" {
- return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "%s: plugin kind is required", path)
- }
- if plugin.Spec == nil {
- return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "%s: plugin spec is required", path)
- }
- // Re-marshal the spec and unmarshal into the typed struct.
- specJSON, err := json.Marshal(plugin.Spec)
- if err != nil {
- return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "%s.spec", path)
- }
- target := factory()
- decoder := json.NewDecoder(bytes.NewReader(specJSON))
- decoder.DisallowUnknownFields()
- if err := decoder.Decode(target); err != nil {
- return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "%s.spec", path)
- }
- if err := validator.New().Struct(target); err != nil {
- return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "%s.spec", path)
- }
- // Write the typed struct back so defaults are included.
- plugin.Spec = target
- return nil
-}
-
-// validateQueryAllowedForPanel checks that the query plugin kind is permitted
-// for the given panel. For composite queries it recurses into sub-queries.
-func validateQueryAllowedForPanel(plugin common.Plugin, allowed []QueryPluginKind, panelKind PanelPluginKind, path string) error {
- queryKind := QueryPluginKind(plugin.Kind)
- if !slices.Contains(allowed, queryKind) {
- return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput,
- "%s: query kind %q is not supported by panel kind %q", path, queryKind, panelKind)
- }
-
- // For composite queries, validate each sub-query type.
- if queryKind == QueryKindComposite && plugin.Spec != nil {
- specJSON, err := json.Marshal(plugin.Spec)
- if err != nil {
- return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "%s.spec", path)
- }
- var composite struct {
- Queries []struct {
- Type qb.QueryType `json:"type"`
- } `json:"queries"`
- }
- if err := json.Unmarshal(specJSON, &composite); err != nil {
- return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "%s.spec", path)
- }
- for si, sub := range composite.Queries {
- pluginKind, ok := compositeSubQueryTypeToPluginKind[sub.Type]
- if !ok {
- continue
- }
- if !slices.Contains(allowed, pluginKind) {
- return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput,
- "%s.spec.queries[%d]: sub-query type %q is not supported by panel kind %q",
- path, si, sub.Type, panelKind)
- }
- }
- }
- return nil
-}
diff --git a/pkg/types/dashboardtypes/perses_dashboard_data.go b/pkg/types/dashboardtypes/perses_dashboard_data.go
new file mode 100644
index 0000000000..5e83ff79cd
--- /dev/null
+++ b/pkg/types/dashboardtypes/perses_dashboard_data.go
@@ -0,0 +1,107 @@
+package dashboardtypes
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "slices"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ qb "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ v1 "github.com/perses/perses/pkg/model/api/v1"
+ "github.com/perses/perses/pkg/model/api/v1/common"
+)
+
+// DashboardData is the SigNoz dashboard v2 spec shape. It mirrors
+// v1.DashboardSpec (Perses) field-for-field, except every common.Plugin
+// occurrence is replaced with a typed SigNoz plugin whose OpenAPI schema is a
+// per-site discriminated oneOf.
+type DashboardData struct {
+ Display *common.Display `json:"display,omitempty"`
+ Datasources map[string]*DatasourceSpec `json:"datasources,omitempty"`
+ Variables []Variable `json:"variables,omitempty"`
+ Panels map[string]*Panel `json:"panels"`
+ Layouts []Layout `json:"layouts"`
+ Duration common.DurationString `json:"duration"`
+ RefreshInterval common.DurationString `json:"refreshInterval,omitempty"`
+ Links []v1.Link `json:"links,omitempty"`
+}
+
+// ══════════════════════════════════════════════
+// Unmarshal + validate entry point
+// ══════════════════════════════════════════════
+
+func (d *DashboardData) UnmarshalJSON(data []byte) error {
+ dec := json.NewDecoder(bytes.NewReader(data))
+ dec.DisallowUnknownFields()
+ type alias DashboardData
+ var tmp alias
+ if err := dec.Decode(&tmp); err != nil {
+ return errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid dashboard spec")
+ }
+ *d = DashboardData(tmp)
+ return d.Validate()
+}
+
+// ══════════════════════════════════════════════
+// Cross-field validation
+// ══════════════════════════════════════════════
+
+func (d *DashboardData) Validate() error {
+ for key, panel := range d.Panels {
+ if panel == nil {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "spec.panels.%s: panel must not be null", key)
+ }
+ path := fmt.Sprintf("spec.panels.%s", key)
+ panelKind := panel.Spec.Plugin.Kind
+ if len(panel.Spec.Queries) != 1 {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "%s.spec.queries: panel must have one query", path)
+ }
+ allowed := allowedQueryKinds[panelKind]
+ for qi, q := range panel.Spec.Queries {
+ queryPath := fmt.Sprintf("%s.spec.queries[%d].spec.plugin", path, qi)
+ if err := validateQueryAllowedForPanel(q.Spec.Plugin, allowed, panelKind, queryPath); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func validateQueryAllowedForPanel(plugin QueryPlugin, allowed []QueryPluginKind, panelKind PanelPluginKind, path string) error {
+ if !slices.Contains(allowed, plugin.Kind) {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput,
+ "%s: query kind %q is not supported by panel kind %q", path, plugin.Kind, panelKind)
+ }
+
+ if plugin.Kind != QueryKindComposite {
+ return nil
+ }
+ composite, ok := plugin.Spec.(*CompositeQuerySpec)
+ if !ok || composite == nil {
+ // Unreachable via UnmarshalJSON; reaching here means a Go caller broke the Kind/Spec pairing.
+ return errors.NewInternalf(errors.CodeInternal, "%s: composite query plugin has unexpected spec type %T", path, plugin.Spec)
+ }
+ for si, sub := range composite.Queries {
+ subKind, ok := compositeSubQueryTypeToPluginKind[sub.Type]
+ if !ok {
+ continue
+ }
+ if !slices.Contains(allowed, subKind) {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput,
+ "%s.spec.queries[%d]: sub-query type %q is not supported by panel kind %q",
+ path, si, sub.Type, panelKind)
+ }
+ }
+ return nil
+}
+
+var (
+ compositeSubQueryTypeToPluginKind = map[qb.QueryType]QueryPluginKind{
+ qb.QueryTypeBuilder: QueryKindBuilder,
+ qb.QueryTypeFormula: QueryKindFormula,
+ qb.QueryTypeTraceOperator: QueryKindTraceOperator,
+ qb.QueryTypePromQL: QueryKindPromQL,
+ qb.QueryTypeClickHouseSQL: QueryKindClickHouseSQL,
+ }
+)
diff --git a/pkg/types/dashboardtypes/dashboard_v2_test.go b/pkg/types/dashboardtypes/perses_dashboard_test.go
similarity index 81%
rename from pkg/types/dashboardtypes/dashboard_v2_test.go
rename to pkg/types/dashboardtypes/perses_dashboard_test.go
index 1417cc16b3..8a7a09dbbe 100644
--- a/pkg/types/dashboardtypes/dashboard_v2_test.go
+++ b/pkg/types/dashboardtypes/perses_dashboard_test.go
@@ -7,33 +7,75 @@ import (
"testing"
"time"
+ "github.com/SigNoz/signoz/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
+func unmarshalDashboard(data []byte) (*DashboardData, error) {
+ var d DashboardData
+ if err := json.Unmarshal(data, &d); err != nil {
+ return nil, err
+ }
+ return &d, nil
+}
+
func TestValidateBigExample(t *testing.T) {
data, err := os.ReadFile("testdata/perses.json")
require.NoError(t, err, "reading example file")
- _, err = UnmarshalAndValidateDashboardV2JSON(data)
+ _, err = unmarshalDashboard(data)
require.NoError(t, err, "expected valid dashboard")
}
func TestValidateDashboardWithSections(t *testing.T) {
data, err := os.ReadFile("testdata/perses_with_sections.json")
require.NoError(t, err, "reading example file")
- _, err = UnmarshalAndValidateDashboardV2JSON(data)
+ _, err = unmarshalDashboard(data)
require.NoError(t, err, "expected valid dashboard")
}
func TestInvalidateNotAJSON(t *testing.T) {
- _, err := UnmarshalAndValidateDashboardV2JSON([]byte("not json"))
+ _, err := unmarshalDashboard([]byte("not json"))
require.Error(t, err, "expected error for invalid JSON")
}
+// TestUnmarshalErrorPreservesNestedMessage guards the wrap on dec.Decode in
+// DashboardData.UnmarshalJSON. The wrap stamps a consistent type/code on
+// decode failures, but must not smother the rich messages produced by nested
+// UnmarshalJSON methods (panel/query/variable/datasource plugin envelopes).
+func TestUnmarshalErrorPreservesNestedMessage(t *testing.T) {
+ data := []byte(`{
+ "panels": {
+ "p1": {
+ "kind": "Panel",
+ "spec": {
+ "plugin": {"kind": "NonExistentPanel", "spec": {}}
+ }
+ }
+ },
+ "layouts": []
+ }`)
+
+ _, err := unmarshalDashboard(data)
+ require.Error(t, err)
+
+ require.Contains(t, err.Error(), "unknown panel plugin kind",
+ "outer wrap should not smother the inner UnmarshalJSON message")
+ require.Contains(t, err.Error(), `"NonExistentPanel"`,
+ "the offending value should still appear in the error")
+ require.Contains(t, err.Error(), "allowed values:",
+ "the allowed-values hint should still appear in the error")
+
+ assert.True(t, errors.Ast(err, errors.TypeInvalidInput),
+ "outer wrap should classify the error as TypeInvalidInput")
+ assert.True(t, errors.Asc(err, ErrCodeDashboardInvalidInput),
+ "outer wrap should stamp ErrCodeDashboardInvalidInput")
+}
+
func TestValidateEmptySpec(t *testing.T) {
// no variables no panels
data := []byte(`{}`)
- _, err := UnmarshalAndValidateDashboardV2JSON(data)
+ _, err := unmarshalDashboard(data)
require.NoError(t, err, "expected valid")
}
@@ -59,17 +101,13 @@ func TestValidateOnlyVariables(t *testing.T) {
"kind": "TextVariable",
"spec": {
"name": "mytext",
- "value": "default",
- "plugin": {
- "kind": "signoz/TextboxVariable",
- "spec": {}
- }
+ "value": "default"
}
}
],
"layouts": []
}`)
- _, err := UnmarshalAndValidateDashboardV2JSON(data)
+ _, err := unmarshalDashboard(data)
require.NoError(t, err, "expected valid")
}
@@ -148,7 +186,7 @@ func TestInvalidateUnknownPluginKind(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- _, err := UnmarshalAndValidateDashboardV2JSON([]byte(tt.data))
+ _, err := unmarshalDashboard([]byte(tt.data))
require.Error(t, err, "expected error containing %q, got nil", tt.wantContain)
require.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)
})
@@ -169,7 +207,7 @@ func TestInvalidateOneInvalidPanel(t *testing.T) {
},
"layouts": []
}`)
- _, err := UnmarshalAndValidateDashboardV2JSON(data)
+ _, err := unmarshalDashboard(data)
require.Error(t, err, "expected error for invalid panel plugin kind")
require.Contains(t, err.Error(), "FakePanel", "error should mention FakePanel")
}
@@ -245,7 +283,7 @@ func TestRejectUnknownFieldsInPluginSpec(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- _, err := UnmarshalAndValidateDashboardV2JSON([]byte(tt.data))
+ _, err := unmarshalDashboard([]byte(tt.data))
require.Error(t, err, "expected error for unknown field")
require.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)
})
@@ -323,7 +361,7 @@ func TestInvalidateWrongFieldTypeInPluginSpec(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- _, err := UnmarshalAndValidateDashboardV2JSON([]byte(tt.data))
+ _, err := unmarshalDashboard([]byte(tt.data))
require.Error(t, err, "expected validation error")
if tt.wantContain != "" {
require.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)
@@ -531,13 +569,69 @@ func TestInvalidateBadPanelSpecValues(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- _, err := UnmarshalAndValidateDashboardV2JSON([]byte(tt.data))
+ _, err := unmarshalDashboard([]byte(tt.data))
require.Error(t, err, "expected error containing %q, got nil", tt.wantContain)
require.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)
})
}
}
+func TestInvalidatePanelWithoutQueries(t *testing.T) {
+ data := []byte(`{
+ "panels": {
+ "p1": {
+ "kind": "Panel",
+ "spec": {"plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}}}
+ }
+ },
+ "layouts": []
+ }`)
+ _, err := unmarshalDashboard(data)
+ require.Error(t, err, "expected panel-without-queries to be rejected")
+ require.Contains(t, err.Error(), "panel must have one query")
+}
+
+func TestInvalidatePanelWithEmptyQueriesArray(t *testing.T) {
+ data := []byte(`{
+ "panels": {
+ "p1": {
+ "kind": "Panel",
+ "spec": {
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": []
+ }
+ }
+ },
+ "layouts": []
+ }`)
+ _, err := unmarshalDashboard(data)
+ require.Error(t, err, "expected panel with explicit empty queries array to be rejected")
+ require.Contains(t, err.Error(), "panel must have one query")
+}
+
+// Rendering multiple data sources in a single panel is supported via
+// signoz/CompositeQuery, not by listing multiple top-level queries.
+func TestInvalidatePanelWithMultipleDirectQueries(t *testing.T) {
+ data := []byte(`{
+ "panels": {
+ "p1": {
+ "kind": "Panel",
+ "spec": {
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": [
+ {"kind": "TimeSeriesQuery", "spec": {"plugin": {"kind": "signoz/BuilderQuery", "spec": {"name": "A", "signal": "metrics"}}}},
+ {"kind": "TimeSeriesQuery", "spec": {"plugin": {"kind": "signoz/BuilderQuery", "spec": {"name": "B", "signal": "metrics"}}}}
+ ]
+ }
+ }
+ },
+ "layouts": []
+ }`)
+ _, err := unmarshalDashboard(data)
+ require.Error(t, err, "expected panel with two top-level queries to be rejected")
+ require.Contains(t, err.Error(), "panel must have one query")
+}
+
func TestValidateRequiredFields(t *testing.T) {
wrapVariable := func(pluginKind, pluginSpec string) string {
return `{
@@ -626,7 +720,7 @@ func TestValidateRequiredFields(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- _, err := UnmarshalAndValidateDashboardV2JSON([]byte(tt.data))
+ _, err := unmarshalDashboard([]byte(tt.data))
require.Error(t, err, "expected error containing %q, got nil", tt.wantContain)
require.Contains(t, err.Error(), tt.wantContain, "error should mention %q", tt.wantContain)
})
@@ -642,13 +736,14 @@ func TestTimeSeriesPanelDefaults(t *testing.T) {
"plugin": {
"kind": "signoz/TimeSeriesPanel",
"spec": {}
- }
+ },
+ "queries": [{"kind": "TimeSeriesQuery", "spec": {"plugin": {"kind": "signoz/PromQLQuery", "spec": {"name": "A", "query": "up"}}}}]
}
}
},
"layouts": []
}`)
- d, err := UnmarshalAndValidateDashboardV2JSON(data)
+ d, err := unmarshalDashboard(data)
require.NoError(t, err, "unmarshal and validate failed")
// After validation+normalization, the plugin spec should be a typed struct.
@@ -689,13 +784,14 @@ func TestNumberPanelDefaults(t *testing.T) {
"plugin": {
"kind": "signoz/NumberPanel",
"spec": {"thresholds": [{"value": 100, "color": "Red"}]}
- }
+ },
+ "queries": [{"kind": "TimeSeriesQuery", "spec": {"plugin": {"kind": "signoz/PromQLQuery", "spec": {"name": "A", "query": "up"}}}}]
}
}
},
"layouts": []
}`)
- d, err := UnmarshalAndValidateDashboardV2JSON(data)
+ d, err := unmarshalDashboard(data)
require.NoError(t, err, "unmarshal and validate failed")
require.IsType(t, &NumberPanelSpec{}, d.Panels["p1"].Spec.Plugin.Spec)
@@ -716,6 +812,30 @@ func TestNumberPanelDefaults(t *testing.T) {
"expected stored/response JSON to contain operator:>, got: %s", outputStr)
}
+// TestPersesFixtureStorageRoundTrip exercises the typed → map[string]any →
+// typed cycle that the create/get path performs against the kitchen-sink
+// fixture. Catches plugin specs whose UnmarshalJSON expects a different shape
+// than the default MarshalJSON emits.
+func TestPersesFixtureStorageRoundTrip(t *testing.T) {
+ raw, err := os.ReadFile("testdata/perses.json")
+ require.NoError(t, err)
+
+ var data DashboardData
+ require.NoError(t, json.Unmarshal(raw, &data), "initial unmarshal")
+
+ marshaled, err := json.Marshal(data)
+ require.NoError(t, err, "marshal typed → JSON")
+
+ var asMap map[string]any
+ require.NoError(t, json.Unmarshal(marshaled, &asMap), "JSON → map (storage shape)")
+
+ remarshaled, err := json.Marshal(asMap)
+ require.NoError(t, err, "map → JSON (read-back shape)")
+
+ var roundtripped DashboardData
+ require.NoError(t, json.Unmarshal(remarshaled, &roundtripped), "JSON → typed (the failure mode)")
+}
+
// TestStorageRoundTrip simulates the future DB store/load cycle:
// marshal the normalized dashboard to JSON (what would be written to DB),
// then unmarshal it back (what would be read from DB), and verify defaults survive.
@@ -728,7 +848,8 @@ func TestStorageRoundTrip(t *testing.T) {
"plugin": {
"kind": "signoz/TimeSeriesPanel",
"spec": {}
- }
+ },
+ "queries": [{"kind": "TimeSeriesQuery", "spec": {"plugin": {"kind": "signoz/PromQLQuery", "spec": {"name": "A", "query": "up"}}}}]
}
},
"p2": {
@@ -737,7 +858,8 @@ func TestStorageRoundTrip(t *testing.T) {
"plugin": {
"kind": "signoz/NumberPanel",
"spec": {"thresholds": [{"value": 100, "color": "Red"}]}
- }
+ },
+ "queries": [{"kind": "TimeSeriesQuery", "spec": {"plugin": {"kind": "signoz/PromQLQuery", "spec": {"name": "A", "query": "up"}}}}]
}
}
},
@@ -745,7 +867,7 @@ func TestStorageRoundTrip(t *testing.T) {
}`)
// Step 1: Unmarshal + validate + normalize (what the API handler does).
- d, err := UnmarshalAndValidateDashboardV2JSON(input)
+ d, err := unmarshalDashboard(input)
require.NoError(t, err, "unmarshal and validate failed")
// Step 1.5: Verify struct fields have correct defaults (extra validation before storing).
@@ -765,7 +887,7 @@ func TestStorageRoundTrip(t *testing.T) {
require.NoError(t, err, "marshal for storage failed")
// Step 3: Unmarshal from JSON (simulates reading from DB).
- loaded, err := UnmarshalAndValidateDashboardV2JSON(stored)
+ loaded, err := unmarshalDashboard(stored)
require.NoError(t, err, "unmarshal from storage failed")
// Step 3.5: Verify struct fields have correct defaults after loading (before returning in API).
@@ -878,7 +1000,7 @@ func TestPanelTypeQueryTypeCompatibility(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- _, err := UnmarshalAndValidateDashboardV2JSON(tc.data)
+ _, err := unmarshalDashboard(tc.data)
if tc.wantErr {
require.Error(t, err)
} else {
diff --git a/pkg/types/dashboardtypes/perses_drift_test.go b/pkg/types/dashboardtypes/perses_drift_test.go
new file mode 100644
index 0000000000..2c3ab8da88
--- /dev/null
+++ b/pkg/types/dashboardtypes/perses_drift_test.go
@@ -0,0 +1,170 @@
+package dashboardtypes
+
+// TestDashboardDataMatchesPerses asserts that DashboardData
+// and every nested SigNoz-owned type cover the JSON field set of their Perses
+// counterpart.
+
+import (
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+
+ v1 "github.com/perses/perses/pkg/model/api/v1"
+ "github.com/perses/perses/pkg/model/api/v1/dashboard"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestDashboardDataMatchesPerses(t *testing.T) {
+ cases := []struct {
+ name string
+ ours reflect.Type
+ perses reflect.Type
+ }{
+ {"DashboardSpec", typeOf[DashboardData](), typeOf[v1.DashboardSpec]()},
+ {"Panel", typeOf[Panel](), typeOf[v1.Panel]()},
+ {"PanelSpec", typeOf[PanelSpec](), typeOf[v1.PanelSpec]()},
+ {"Query", typeOf[Query](), typeOf[v1.Query]()},
+ {"QuerySpec", typeOf[QuerySpec](), typeOf[v1.QuerySpec]()},
+ {"DatasourceSpec", typeOf[DatasourceSpec](), typeOf[v1.DatasourceSpec]()},
+ {"Variable", typeOf[Variable](), typeOf[dashboard.Variable]()},
+ {"ListVariableSpec", typeOf[ListVariableSpec](), typeOf[dashboard.ListVariableSpec]()},
+ {"Layout", typeOf[Layout](), typeOf[dashboard.Layout]()},
+ }
+
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ missing, extra := drift(c.ours, c.perses)
+
+ assert.Empty(t, missing,
+ "DashboardData (%s) is missing json fields present on Perses %s — upstream likely added or renamed a field",
+ c.ours.Name(), c.perses.Name())
+ assert.Empty(t, extra,
+ "DashboardData (%s) has json fields absent on Perses %s — upstream likely removed a field or we added one without the counterpart",
+ c.ours.Name(), c.perses.Name())
+ })
+ }
+}
+
+func TestDriftDetectionMechanics(t *testing.T) {
+ t.Run("upstream added a field", func(t *testing.T) {
+ type ours struct {
+ Name string `json:"name"`
+ }
+ type perses struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ }
+ missing, extra := drift(typeOf[ours](), typeOf[perses]())
+ assert.Equal(t, []string{"description"}, missing, "missing fires: upstream has a field we don't")
+ assert.Empty(t, extra)
+ })
+
+ t.Run("upstream removed a field", func(t *testing.T) {
+ type ours struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ }
+ type perses struct {
+ Name string `json:"name"`
+ }
+ missing, extra := drift(typeOf[ours](), typeOf[perses]())
+ assert.Empty(t, missing)
+ assert.Equal(t, []string{"description"}, extra, "extra fires: we kept a field upstream removed")
+ })
+
+ t.Run("upstream renamed a field", func(t *testing.T) {
+ type ours struct {
+ Name string `json:"name"`
+ }
+ type perses struct {
+ Name string `json:"title"`
+ }
+ missing, extra := drift(typeOf[ours](), typeOf[perses]())
+ assert.Equal(t, []string{"title"}, missing, "missing fires for the new name")
+ assert.Equal(t, []string{"name"}, extra, "extra fires for the old name — both fire on a rename")
+ })
+
+ t.Run("we added a field upstream does not have", func(t *testing.T) {
+ type ours struct {
+ Name string `json:"name"`
+ Internal string `json:"internal"`
+ }
+ type perses struct {
+ Name string `json:"name"`
+ }
+ missing, extra := drift(typeOf[ours](), typeOf[perses]())
+ assert.Empty(t, missing)
+ assert.Equal(t, []string{"internal"}, extra, "extra fires: we added a field with no upstream counterpart")
+ })
+
+ t.Run("embedded struct flattens — drift inside the embed is caught", func(t *testing.T) {
+ type embedded struct {
+ Display string `json:"display"`
+ NewBit string `json:"newBit"` // upstream added this inside the embed
+ }
+ type ours struct {
+ Display string `json:"display"`
+ Name string `json:"name"`
+ }
+ type perses struct {
+ embedded `json:",inline"`
+ Name string `json:"name"`
+ }
+ missing, extra := drift(typeOf[ours](), typeOf[perses]())
+ assert.Equal(t, []string{"newBit"}, missing, "field added inside an inlined embed surfaces at the parent level")
+ assert.Empty(t, extra)
+ })
+}
+
+func drift(ours, perses reflect.Type) (missing, extra []string) {
+ o, p := jsonFields(ours), jsonFields(perses)
+ return sortedDiff(p, o), sortedDiff(o, p)
+}
+
+// jsonFields returns the set of json tag names for a struct, flattening
+// anonymous embedded fields (matching encoding/json behavior).
+func jsonFields(t reflect.Type) map[string]struct{} {
+ out := map[string]struct{}{}
+ if t.Kind() != reflect.Struct {
+ return out
+ }
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ // Skip unexported fields (e.g., dashboard.ListVariableSpec has an
+ // unexported `variableSpec` interface tag).
+ if !f.IsExported() && !f.Anonymous {
+ continue
+ }
+ tag := f.Tag.Get("json")
+ name := strings.Split(tag, ",")[0]
+ // Anonymous embed with empty json name (no tag, or `json:",inline"` /
+ // `json:",omitempty"`-style options-only tag) is flattened by encoding/json.
+ if f.Anonymous && name == "" {
+ for k := range jsonFields(f.Type) {
+ out[k] = struct{}{}
+ }
+ continue
+ }
+ if tag == "-" || name == "" {
+ continue
+ }
+ out[name] = struct{}{}
+ }
+ return out
+}
+
+// sortedDiff returns keys in a but not in b, sorted.
+func sortedDiff(a, b map[string]struct{}) []string {
+ var diff []string
+ for k := range a {
+ if _, ok := b[k]; !ok {
+ diff = append(diff, k)
+ }
+ }
+ sort.Strings(diff)
+ return diff
+}
+
+func typeOf[T any]() reflect.Type { return reflect.TypeOf((*T)(nil)).Elem() }
diff --git a/pkg/types/dashboardtypes/perses_plugin_wrappers.go b/pkg/types/dashboardtypes/perses_plugin_wrappers.go
new file mode 100644
index 0000000000..f3816ade20
--- /dev/null
+++ b/pkg/types/dashboardtypes/perses_plugin_wrappers.go
@@ -0,0 +1,312 @@
+package dashboardtypes
+
+import (
+ "bytes"
+ "encoding/json"
+ "maps"
+ "slices"
+ "strings"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+
+ "github.com/go-playground/validator/v10"
+ "github.com/swaggest/jsonschema-go"
+)
+
+// ══════════════════════════════════════════════
+// Panel plugin
+// ══════════════════════════════════════════════
+
+type PanelPlugin struct {
+ Kind PanelPluginKind `json:"kind"`
+ Spec any `json:"spec"`
+}
+
+// PrepareJSONSchema drops the reflected struct shape (type: object, properties)
+// from the envelope so that only the JSONSchemaOneOf result binds.
+func (PanelPlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return clearOneOfParentShape(s)
+}
+
+func (p *PanelPlugin) UnmarshalJSON(data []byte) error {
+ kind, specJSON, err := extractKindAndSpec(data)
+ if err != nil {
+ return err
+ }
+ factory, ok := panelPluginSpecs[PanelPluginKind(kind)]
+ if !ok {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "unknown panel plugin kind %q; allowed values: %s", kind, allowedValuesForKind(slices.Sorted(maps.Keys(panelPluginSpecs))))
+ }
+ spec, err := decodeSpec(specJSON, factory(), kind)
+ if err != nil {
+ return err
+ }
+ p.Kind = PanelPluginKind(kind)
+ p.Spec = spec
+ return nil
+}
+
+func (PanelPlugin) JSONSchemaOneOf() []any {
+ return []any{
+ PanelPluginVariant[TimeSeriesPanelSpec]{Kind: string(PanelKindTimeSeries)},
+ PanelPluginVariant[BarChartPanelSpec]{Kind: string(PanelKindBarChart)},
+ PanelPluginVariant[NumberPanelSpec]{Kind: string(PanelKindNumber)},
+ PanelPluginVariant[PieChartPanelSpec]{Kind: string(PanelKindPieChart)},
+ PanelPluginVariant[TablePanelSpec]{Kind: string(PanelKindTable)},
+ PanelPluginVariant[HistogramPanelSpec]{Kind: string(PanelKindHistogram)},
+ PanelPluginVariant[ListPanelSpec]{Kind: string(PanelKindList)},
+ }
+}
+
+type PanelPluginVariant[S any] struct {
+ Kind string `json:"kind" required:"true"`
+ Spec S `json:"spec" required:"true"`
+}
+
+func (v PanelPluginVariant[S]) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return restrictKindToOneValue(s, v.Kind)
+}
+
+// ══════════════════════════════════════════════
+// Query plugin
+// ══════════════════════════════════════════════
+
+type QueryPlugin struct {
+ Kind QueryPluginKind `json:"kind"`
+ Spec any `json:"spec"`
+}
+
+func (QueryPlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return clearOneOfParentShape(s)
+}
+
+func (p *QueryPlugin) UnmarshalJSON(data []byte) error {
+ kind, specJSON, err := extractKindAndSpec(data)
+ if err != nil {
+ return err
+ }
+ factory, ok := queryPluginSpecs[QueryPluginKind(kind)]
+ if !ok {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "unknown query plugin kind %q; allowed values: %s", kind, allowedValuesForKind(slices.Sorted(maps.Keys(queryPluginSpecs))))
+ }
+ spec, err := decodeSpec(specJSON, factory(), kind)
+ if err != nil {
+ return err
+ }
+ p.Kind = QueryPluginKind(kind)
+ p.Spec = spec
+ return nil
+}
+
+func (QueryPlugin) JSONSchemaOneOf() []any {
+ return []any{
+ QueryPluginVariant[BuilderQuerySpec]{Kind: string(QueryKindBuilder)},
+ QueryPluginVariant[CompositeQuerySpec]{Kind: string(QueryKindComposite)},
+ QueryPluginVariant[FormulaSpec]{Kind: string(QueryKindFormula)},
+ QueryPluginVariant[PromQLQuerySpec]{Kind: string(QueryKindPromQL)},
+ QueryPluginVariant[ClickHouseSQLQuerySpec]{Kind: string(QueryKindClickHouseSQL)},
+ QueryPluginVariant[TraceOperatorSpec]{Kind: string(QueryKindTraceOperator)},
+ }
+}
+
+type QueryPluginVariant[S any] struct {
+ Kind string `json:"kind" required:"true"`
+ Spec S `json:"spec" required:"true"`
+}
+
+func (v QueryPluginVariant[S]) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return restrictKindToOneValue(s, v.Kind)
+}
+
+// ══════════════════════════════════════════════
+// Variable plugin
+// ══════════════════════════════════════════════
+
+type VariablePlugin struct {
+ Kind VariablePluginKind `json:"kind"`
+ Spec any `json:"spec"`
+}
+
+func (VariablePlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return clearOneOfParentShape(s)
+}
+
+func (p *VariablePlugin) UnmarshalJSON(data []byte) error {
+ kind, specJSON, err := extractKindAndSpec(data)
+ if err != nil {
+ return err
+ }
+ factory, ok := variablePluginSpecs[VariablePluginKind(kind)]
+ if !ok {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "unknown variable plugin kind %q; allowed values: %s", kind, allowedValuesForKind(slices.Sorted(maps.Keys(variablePluginSpecs))))
+ }
+ spec, err := decodeSpec(specJSON, factory(), kind)
+ if err != nil {
+ return err
+ }
+ p.Kind = VariablePluginKind(kind)
+ p.Spec = spec
+ return nil
+}
+
+func (VariablePlugin) JSONSchemaOneOf() []any {
+ return []any{
+ VariablePluginVariant[DynamicVariableSpec]{Kind: string(VariableKindDynamic)},
+ VariablePluginVariant[QueryVariableSpec]{Kind: string(VariableKindQuery)},
+ VariablePluginVariant[CustomVariableSpec]{Kind: string(VariableKindCustom)},
+ }
+}
+
+type VariablePluginVariant[S any] struct {
+ Kind string `json:"kind" required:"true"`
+ Spec S `json:"spec" required:"true"`
+}
+
+func (v VariablePluginVariant[S]) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return restrictKindToOneValue(s, v.Kind)
+}
+
+// ══════════════════════════════════════════════
+// Datasource plugin
+// ══════════════════════════════════════════════
+
+type DatasourcePlugin struct {
+ Kind DatasourcePluginKind `json:"kind"`
+ Spec any `json:"spec"`
+}
+
+func (DatasourcePlugin) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return clearOneOfParentShape(s)
+}
+
+func (p *DatasourcePlugin) UnmarshalJSON(data []byte) error {
+ kind, specJSON, err := extractKindAndSpec(data)
+ if err != nil {
+ return err
+ }
+ factory, ok := datasourcePluginSpecs[DatasourcePluginKind(kind)]
+ if !ok {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "unknown datasource plugin kind %q; allowed values: %s", kind, allowedValuesForKind(slices.Sorted(maps.Keys(datasourcePluginSpecs))))
+ }
+ spec, err := decodeSpec(specJSON, factory(), kind)
+ if err != nil {
+ return err
+ }
+ p.Kind = DatasourcePluginKind(kind)
+ p.Spec = spec
+ return nil
+}
+
+func (DatasourcePlugin) JSONSchemaOneOf() []any {
+ return []any{
+ DatasourcePluginVariant[struct{}]{Kind: string(DatasourceKindSigNoz)},
+ }
+}
+
+type DatasourcePluginVariant[S any] struct {
+ Kind string `json:"kind" required:"true"`
+ Spec S `json:"spec" required:"true"`
+}
+
+func (v DatasourcePluginVariant[S]) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return restrictKindToOneValue(s, v.Kind)
+}
+
+// ══════════════════════════════════════════════
+// Helpers
+// ══════════════════════════════════════════════
+
+var (
+ panelPluginSpecs = map[PanelPluginKind]func() any{
+ PanelKindTimeSeries: func() any { return new(TimeSeriesPanelSpec) },
+ PanelKindBarChart: func() any { return new(BarChartPanelSpec) },
+ PanelKindNumber: func() any { return new(NumberPanelSpec) },
+ PanelKindPieChart: func() any { return new(PieChartPanelSpec) },
+ PanelKindTable: func() any { return new(TablePanelSpec) },
+ PanelKindHistogram: func() any { return new(HistogramPanelSpec) },
+ PanelKindList: func() any { return new(ListPanelSpec) },
+ }
+ queryPluginSpecs = map[QueryPluginKind]func() any{
+ QueryKindBuilder: func() any { return new(BuilderQuerySpec) },
+ QueryKindComposite: func() any { return new(CompositeQuerySpec) },
+ QueryKindFormula: func() any { return new(FormulaSpec) },
+ QueryKindPromQL: func() any { return new(PromQLQuerySpec) },
+ QueryKindClickHouseSQL: func() any { return new(ClickHouseSQLQuerySpec) },
+ QueryKindTraceOperator: func() any { return new(TraceOperatorSpec) },
+ }
+ variablePluginSpecs = map[VariablePluginKind]func() any{
+ VariableKindDynamic: func() any { return new(DynamicVariableSpec) },
+ VariableKindQuery: func() any { return new(QueryVariableSpec) },
+ VariableKindCustom: func() any { return new(CustomVariableSpec) },
+ }
+ datasourcePluginSpecs = map[DatasourcePluginKind]func() any{
+ DatasourceKindSigNoz: func() any { return new(struct{}) },
+ }
+
+ allowedQueryKinds = map[PanelPluginKind][]QueryPluginKind{
+ PanelKindTimeSeries: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
+ PanelKindBarChart: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
+ PanelKindNumber: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
+ PanelKindHistogram: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindPromQL, QueryKindClickHouseSQL},
+ PanelKindPieChart: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
+ PanelKindTable: {QueryKindBuilder, QueryKindComposite, QueryKindFormula, QueryKindTraceOperator, QueryKindClickHouseSQL},
+ PanelKindList: {QueryKindBuilder},
+ }
+)
+
+func allowedValuesForKind[K ~string](kinds []K) string {
+ parts := make([]string, len(kinds))
+ for i, k := range kinds {
+ parts[i] = "`" + string(k) + "`"
+ }
+ return strings.Join(parts, ", ")
+}
+
+// extractKindAndSpec parses a {"kind": "...", "spec": {...}} envelope and returns
+// kind and the raw spec bytes for typed decoding.
+func extractKindAndSpec(data []byte) (string, []byte, error) {
+ var head struct {
+ Kind string `json:"kind"`
+ Spec json.RawMessage `json:"spec"`
+ }
+ if err := json.Unmarshal(data, &head); err != nil {
+ return "", nil, errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "invalid plugin envelope")
+ }
+ return head.Kind, head.Spec, nil
+}
+
+// decodeSpec strict-decodes a spec JSON into target and runs struct-tag validation (go-playground/validator).
+func decodeSpec(specJSON []byte, target any, kind string) (any, error) {
+ if len(specJSON) == 0 {
+ return nil, errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "kind %q: spec is required", kind)
+ }
+ dec := json.NewDecoder(bytes.NewReader(specJSON))
+ dec.DisallowUnknownFields()
+ if err := dec.Decode(target); err != nil {
+ return nil, errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "kind %q: invalid spec JSON", kind)
+ }
+ if err := validator.New().Struct(target); err != nil {
+ return nil, errors.WrapInvalidInputf(err, ErrCodeDashboardInvalidInput, "kind %q: spec failed validation", kind)
+ }
+ return target, nil
+}
+
+// clearOneOfParentShape drops Type and Properties on a schema that also has a JSONSchemaOneOf.
+func clearOneOfParentShape(s *jsonschema.Schema) error {
+ s.Type = nil
+ s.Properties = nil
+ return nil
+}
+
+// restrictKindToOneValue ensures that the schema only allows one Kind value for a type.
+// For eg. PanelPluginVariant[TimeSeriesPanelSpec]{Kind: string(PanelKindTimeSeries)} should
+// only allow "signoz/TimeSeriesPanel" in its kind field.
+func restrictKindToOneValue(schema *jsonschema.Schema, kind string) error {
+ kindProp, ok := schema.Properties["kind"]
+ if !ok || kindProp.TypeObject == nil {
+ return errors.NewInternalf(errors.CodeInternal, "variant schema missing `kind` property")
+ }
+ kindProp.TypeObject.WithEnum(kind)
+ schema.Properties["kind"] = kindProp
+ return nil
+}
diff --git a/pkg/types/dashboardtypes/perses_replicas.go b/pkg/types/dashboardtypes/perses_replicas.go
new file mode 100644
index 0000000000..1434ab42f3
--- /dev/null
+++ b/pkg/types/dashboardtypes/perses_replicas.go
@@ -0,0 +1,182 @@
+package dashboardtypes
+
+import (
+ "maps"
+ "slices"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ v1 "github.com/perses/perses/pkg/model/api/v1"
+ "github.com/perses/perses/pkg/model/api/v1/common"
+ "github.com/perses/perses/pkg/model/api/v1/dashboard"
+ "github.com/perses/perses/pkg/model/api/v1/variable"
+ "github.com/swaggest/jsonschema-go"
+)
+
+// ══════════════════════════════════════════════
+// Datasource
+// ══════════════════════════════════════════════
+
+type DatasourceSpec struct {
+ Display *common.Display `json:"display,omitempty"`
+ Default bool `json:"default"`
+ Plugin DatasourcePlugin `json:"plugin"`
+}
+
+// ══════════════════════════════════════════════
+// Panel
+// ══════════════════════════════════════════════
+
+type Panel struct {
+ Kind string `json:"kind"`
+ Spec PanelSpec `json:"spec"`
+}
+
+type PanelSpec struct {
+ Display *v1.PanelDisplay `json:"display,omitempty"`
+ Plugin PanelPlugin `json:"plugin"`
+ Queries []Query `json:"queries,omitempty"`
+ Links []v1.Link `json:"links,omitempty"`
+}
+
+// ══════════════════════════════════════════════
+// Query
+// ══════════════════════════════════════════════
+
+type Query struct {
+ Kind string `json:"kind"`
+ Spec QuerySpec `json:"spec"`
+}
+
+type QuerySpec struct {
+ Name string `json:"name,omitempty"`
+ Plugin QueryPlugin `json:"plugin"`
+}
+
+// ══════════════════════════════════════════════
+// Variable
+// ══════════════════════════════════════════════
+
+// Variable is the list/text sum type. Spec is set to *ListVariableSpec or
+// *dashboard.TextVariableSpec by UnmarshalJSON based on Kind. The schema is a
+// discriminated oneOf (see JSONSchemaOneOf).
+type Variable struct {
+ Kind variable.Kind `json:"kind"`
+ Spec any `json:"spec"`
+}
+
+func (Variable) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return clearOneOfParentShape(s)
+}
+
+func (v *Variable) UnmarshalJSON(data []byte) error {
+ kind, specJSON, err := extractKindAndSpec(data)
+ if err != nil {
+ return err
+ }
+ switch kind {
+ case string(variable.KindList):
+ spec, err := decodeSpec(specJSON, new(ListVariableSpec), kind)
+ if err != nil {
+ return err
+ }
+ v.Kind = variable.KindList
+ v.Spec = spec
+ case string(variable.KindText):
+ spec, err := decodeSpec(specJSON, new(dashboard.TextVariableSpec), kind)
+ if err != nil {
+ return err
+ }
+ v.Kind = variable.KindText
+ v.Spec = spec
+ default:
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "unknown variable kind %q; allowed values: %s", kind, allowedValuesForKind([]variable.Kind{variable.KindList, variable.KindText}))
+ }
+ return nil
+}
+
+func (Variable) JSONSchemaOneOf() []any {
+ return []any{
+ VariableEnvelope[ListVariableSpec]{Kind: string(variable.KindList)},
+ VariableEnvelope[dashboard.TextVariableSpec]{Kind: string(variable.KindText)},
+ }
+}
+
+type VariableEnvelope[S any] struct {
+ Kind string `json:"kind" required:"true"`
+ Spec S `json:"spec" required:"true"`
+}
+
+func (v VariableEnvelope[S]) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return restrictKindToOneValue(s, v.Kind)
+}
+
+// ListVariableSpec mirrors dashboard.ListVariableSpec (variable.ListSpec
+// fields + Name) but with a typed VariablePlugin replacing common.Plugin.
+type ListVariableSpec struct {
+ Display *variable.Display `json:"display,omitempty"`
+ DefaultValue *variable.DefaultValue `json:"defaultValue,omitempty"`
+ AllowAllValue bool `json:"allowAllValue"`
+ AllowMultiple bool `json:"allowMultiple"`
+ CustomAllValue string `json:"customAllValue,omitempty"`
+ CapturingRegexp string `json:"capturingRegexp,omitempty"`
+ Sort *variable.Sort `json:"sort,omitempty"`
+ Plugin VariablePlugin `json:"plugin"`
+ Name string `json:"name"`
+}
+
+// ══════════════════════════════════════════════
+// Layout
+// ══════════════════════════════════════════════
+
+// Layout is the dashboard layout sum type. Spec is populated by UnmarshalJSON
+// with the concrete layout spec struct (today only dashboard.GridLayoutSpec)
+// based on Kind. No plugin is involved, so we reuse the Perses spec types as
+// leaf imports.
+type Layout struct {
+ Kind dashboard.LayoutKind `json:"kind"`
+ Spec any `json:"spec"`
+}
+
+// layoutSpecs is the layout sum type factory. Perses only defines
+// KindGridLayout today; adding a new kind upstream surfaces as an
+// "unknown layout kind" runtime error here until we add it.
+var layoutSpecs = map[dashboard.LayoutKind]func() any{
+ dashboard.KindGridLayout: func() any { return new(dashboard.GridLayoutSpec) },
+}
+
+func (Layout) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return clearOneOfParentShape(s)
+}
+
+func (l *Layout) UnmarshalJSON(data []byte) error {
+ kind, specJSON, err := extractKindAndSpec(data)
+ if err != nil {
+ return err
+ }
+ factory, ok := layoutSpecs[dashboard.LayoutKind(kind)]
+ if !ok {
+ return errors.NewInvalidInputf(ErrCodeDashboardInvalidInput, "unknown layout kind %q; allowed values: %s", kind, allowedValuesForKind(slices.Sorted(maps.Keys(layoutSpecs))))
+ }
+ spec, err := decodeSpec(specJSON, factory(), kind)
+ if err != nil {
+ return err
+ }
+ l.Kind = dashboard.LayoutKind(kind)
+ l.Spec = spec
+ return nil
+}
+
+func (Layout) JSONSchemaOneOf() []any {
+ return []any{
+ LayoutEnvelope[dashboard.GridLayoutSpec]{Kind: string(dashboard.KindGridLayout)},
+ }
+}
+
+type LayoutEnvelope[S any] struct {
+ Kind string `json:"kind" required:"true"`
+ Spec S `json:"spec" required:"true"`
+}
+
+func (v LayoutEnvelope[S]) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return restrictKindToOneValue(s, v.Kind)
+}
diff --git a/pkg/types/dashboardtypes/perses_plugin_types.go b/pkg/types/dashboardtypes/perses_signoz_plugins.go
similarity index 95%
rename from pkg/types/dashboardtypes/perses_plugin_types.go
rename to pkg/types/dashboardtypes/perses_signoz_plugins.go
index 283a25c0db..dcc3bb3d20 100644
--- a/pkg/types/dashboardtypes/perses_plugin_types.go
+++ b/pkg/types/dashboardtypes/perses_signoz_plugins.go
@@ -8,6 +8,7 @@ import (
qb "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/swaggest/jsonschema-go"
)
// ══════════════════════════════════════════════
@@ -20,11 +21,10 @@ const (
VariableKindDynamic VariablePluginKind = "signoz/DynamicVariable"
VariableKindQuery VariablePluginKind = "signoz/QueryVariable"
VariableKindCustom VariablePluginKind = "signoz/CustomVariable"
- VariableKindTextbox VariablePluginKind = "signoz/TextboxVariable"
)
func (VariablePluginKind) Enum() []any {
- return []any{VariableKindDynamic, VariableKindQuery, VariableKindCustom, VariableKindTextbox}
+ return []any{VariableKindDynamic, VariableKindQuery, VariableKindCustom}
}
type DynamicVariableSpec struct {
@@ -42,8 +42,6 @@ type CustomVariableSpec struct {
CustomValue string `json:"customValue" validate:"required" required:"true"`
}
-type TextboxVariableSpec struct{}
-
// ══════════════════════════════════════════════
// SigNoz query plugin specs — aliased from querybuildertypesv5
// ══════════════════════════════════════════════
@@ -87,6 +85,30 @@ func (b *BuilderQuerySpec) UnmarshalJSON(data []byte) error {
return nil
}
+// MarshalJSON delegates to the inner Spec so the on-wire shape matches what
+// UnmarshalJSON expects (a flat builder-query payload with `signal` at the top
+// level). Without this, Go's default would wrap it as {"Spec": {...}} and the
+// signal-dispatch on read would fail.
+func (b BuilderQuerySpec) MarshalJSON() ([]byte, error) {
+ return json.Marshal(b.Spec)
+}
+
+// PrepareJSONSchema drops the reflected struct shape so only the
+// JSONSchemaOneOf result binds.
+func (BuilderQuerySpec) PrepareJSONSchema(s *jsonschema.Schema) error {
+ return clearOneOfParentShape(s)
+}
+
+// JSONSchemaOneOf exposes the three signal-dispatched shapes a builder query
+// can take. Mirrors qb.UnmarshalBuilderQueryBySignal's runtime dispatch.
+func (BuilderQuerySpec) JSONSchemaOneOf() []any {
+ return []any{
+ qb.QueryBuilderQuery[qb.LogAggregation]{},
+ qb.QueryBuilderQuery[qb.MetricAggregation]{},
+ qb.QueryBuilderQuery[qb.TraceAggregation]{},
+ }
+}
+
// ══════════════════════════════════════════════
// SigNoz panel plugin specs
// ══════════════════════════════════════════════
diff --git a/pkg/types/dashboardtypes/testdata/perses.json b/pkg/types/dashboardtypes/testdata/perses.json
index 538a5cea4e..76cf48f607 100644
--- a/pkg/types/dashboardtypes/testdata/perses.json
+++ b/pkg/types/dashboardtypes/testdata/perses.json
@@ -76,11 +76,7 @@
"display": {
"name": "textboxvar"
},
- "value": "defaultvaluegoeshere",
- "plugin": {
- "kind": "signoz/TextboxVariable",
- "spec": {}
- }
+ "value": "defaultvaluegoeshere"
}
}
],