validation

package
v1.2.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 29, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Overview

Package validation provides build-time schema design auditing and runtime document validation for the meshery/schemas repository.

This is a dependency-leaf package: it imports kin-openapi, yaml.v3, and the standard library only. It must NOT import github.com/meshery/meshkit or github.com/meshery/schemas/models. This constraint is architectural — it allows meshkit/schema and model helper methods to import this package without creating cycles.

Three concerns live here:

  • Schema Auditing: validates that OpenAPI schema files follow project conventions (naming, dual-schema pattern, codegen annotations, etc.). Invoked at build time via cmd/validate-schemas.

  • Document Validation: validates JSON documents against OpenAPI schemas at runtime using kin-openapi. Used by Meshery server and CLI.

  • Consumer Auditing: walks consumer repos (meshery/meshery, layer5io/meshery-cloud, layer5labs/meshery-extensions) and diffs their registered endpoints against the schemas endpoint index. Three parsers are registered: consumer_gorilla (Go Gorilla router in meshery/meshery), consumer_echo (Go Echo router in meshery-cloud), and consumer_ts (TypeScript RTK Query endpoints across all three repos). The TS consumer is regex-based — full semantic TS analysis would require the TypeScript compiler, and the migration plan calls for simpler heuristics — and it surfaces wire-format drift such as camelCase → SCREAMING case-flips (`orgID: queryArg.orgId`), snake_case body wrappers (`pattern_data`, `k8s_manifest`), and snake_case params keys outside the pagination envelope. Invoked at review/maintenance time via cmd/consumer-audit.

Index

Constants

View Source
const (
	XAnnotatedBoth        = "Both"
	XAnnotatedCloudOnly   = "Cloud only"
	XAnnotatedMesheryOnly = "Meshery only"
	XAnnotatedNoSchema    = "No schema"

	EndpointStatusActiveBoth                      = "Active - Both"
	EndpointStatusActiveMesheryServer             = "Active - Meshery Server"
	EndpointStatusActiveMesheryCloud              = "Active - Meshery Cloud"
	EndpointStatusActiveMesheryServerMissingCloud = "Active - Meshery Server, Unimplemented Meshery Cloud"
	EndpointStatusActiveMesheryCloudMissingServer = "Active - Meshery Cloud, Unimplemented Meshery Server"
	EndpointStatusUnimplementedBoth               = "Unimplemented Both"
	EndpointStatusUnimplementedMesheryServer      = "Unimplemented Meshery Server"
	EndpointStatusUnimplementedMesheryCloud       = "Unimplemented Meshery Cloud"
)

Variables

This section is empty.

Functions

func AuditedChangedColumns added in v1.1.0

func AuditedChangedColumns(prev, cur ConsumerAuditRow) []string

AuditedChangedColumns returns reconcile-significant generated columns whose values differ between two rows.

func AuditedColumnValue added in v1.0.7

func AuditedColumnValue(row ConsumerAuditRow, columnName string) string

AuditedColumnValue returns the cell value of any generated column by its sheet-header name (e.g. "x-annotated"). Returns "" for an unknown column. The CLI uses it to render before/after diffs against the authoritative column list in generatedColumns.

func GetCamelCaseSuggestion

func GetCamelCaseSuggestion(name string) string

GetCamelCaseSuggestion returns a camelCase suggestion for a name, or empty string if no valid suggestion can be generated.

func HasLowercaseSuffix

func HasLowercaseSuffix(s string) bool

HasLowercaseSuffix returns true if s is a known lowercase-suffix violation.

func HasScreamingIDToken

func HasScreamingIDToken(s string) bool

HasScreamingIDToken returns true if s contains SCREAMING_CASE "ID".

func HasScreamingOperationIDSuffix

func HasScreamingOperationIDSuffix(opID string) bool

HasScreamingOperationIDSuffix checks if an operationId ends with "ID".

func HasUnderscore

func HasUnderscore(s string) bool

HasUnderscore returns true if the string contains an underscore.

func IsBadPathParam

func IsBadPathParam(param string) bool

IsBadPathParam returns true if a path parameter name uses incorrect casing.

func IsCamelCase

func IsCamelCase(s string) bool

IsCamelCase returns true if s starts lowercase with no underscores/hyphens.

func IsKebabCase

func IsKebabCase(s string) bool

IsKebabCase returns true if s is lowercase with hyphens only.

func IsPascalCase

func IsPascalCase(s string) bool

IsPascalCase returns true if s starts uppercase with no underscores/hyphens.

func IsValidDBTag

func IsValidDBTag(s string) bool

IsValidDBTag returns true if the value matches the db tag pattern.

func IsValidOperationID

func IsValidOperationID(opID string) bool

IsValidOperationID checks if an operationId is lower camelCase verbNoun.

func SuggestOperationID

func SuggestOperationID(opID string) string

SuggestOperationID converts a screaming "ID" suffix to "Id".

func SuggestPathParam

func SuggestPathParam(param string) string

SuggestPathParam generates the correct camelCase form for a path parameter.

func ToCamelCase

func ToCamelCase(s string) string

ToCamelCase converts a property name to its expected camelCase form.

Types

type AuditOptions

type AuditOptions struct {
	// RootDir is the repository root directory.
	RootDir string

	// Strict promotes all advisory issues to blocking errors.
	Strict bool

	// Warn includes advisory violations in the output (exit 0).
	Warn bool

	// NoBaseline disables advisory baseline filtering.
	NoBaseline bool

	// StyleDebt includes legacy style debt in advisory output.
	StyleDebt bool

	// ContractDebt includes legacy contract debt in advisory output.
	ContractDebt bool
}

AuditOptions configures the behavior of an Audit run.

type AuditResult

type AuditResult struct {
	// Blocking violations cause the validator to exit non-zero.
	Blocking []Violation

	// Advisory violations are informational warnings.
	Advisory []Violation
}

AuditResult holds the outcome of a full schema audit.

func Audit

func Audit(opts AuditOptions) AuditResult

Audit runs the full schema design validation across all constructs in the repository. It returns blocking and advisory violations.

func (AuditResult) HasBlocking

func (r AuditResult) HasBlocking() bool

HasBlocking returns true if any blocking violations were found.

func (AuditResult) Total

func (r AuditResult) Total() int

Total returns the total number of violations found.

type AuditRow added in v1.0.7

type AuditRow = ConsumerAuditRow

AuditRow remains a short alias used throughout the validation package.

type CasingIssue

type CasingIssue struct {
	Description string
}

CasingIssue describes a single casing violation on a name.

func GetCamelCaseIssues

func GetCamelCaseIssues(name string) []CasingIssue

GetCamelCaseIssues checks a wire identifier (schema property name, OpenAPI query/header parameter name, or any similar camelCase-expected token) for casing violations.

Under the canonical identifier-naming contract (AGENTS.md § Casing rules at a glance, docs/identifier-naming-migration.md §1), wire names are camelCase regardless of DB backing — the snake_case DB column name lives only in `x-oapi-codegen-extra-tags.db`, not on the wire. Accordingly this checker is unconditional: there is no DB-mirroring exception. The legacy-DB-mirrored field set (dbMirroredFields) remains defined for use by matcher.go's consumer-type diff, but it is no longer an exception.

The returned issue descriptions are context-agnostic — each caller (Rule 6 for schema/entity properties, Rule 9 for query/header parameters, etc.) is responsible for adding any context-specific guidance on top of the generic message. Severity is determined at the caller via classifyStyleIssue / the --style-debt / --strict-consistency flags.

type ConsumerAuditOptions added in v1.0.7

type ConsumerAuditOptions struct {
	// Schema repo root (required).
	RootDir string

	// Consumer repos. Empty = skip that consumer.
	MesheryRepo string
	CloudRepo   string

	// TypeScript consumer repos. Each of these points at a checkout whose
	// ui/rtk-query (or equivalent) directories are parsed by the TS
	// consumer auditor. MesheryRepoUI defaults to MesheryRepo when unset
	// because meshery/meshery keeps Go and TS consumers in the same
	// checkout; CloudRepoUI likewise defaults to CloudRepo.
	MesheryRepoUI  string
	CloudRepoUI    string
	ExtensionsRepo string

	// Google Sheets update. Empty = no sheet interaction (dry run).
	SheetID           string
	SheetsCredentials []byte
}

ConsumerAuditOptions configures a single consumer-audit run.

type ConsumerAuditResult added in v1.0.7

type ConsumerAuditResult struct {
	// Analysis results.
	Match *matchResult

	// Reconciled state (nil if no previous state was provided).
	Tracked []TrackedEndpoint

	// NewDeletions are endpoints detected as removed on this run.
	NewDeletions []DeletionRecord

	// Output rows for sheet serialization (sorted, deterministic).
	Rows []AuditRow

	// Summary counts for terminal display.
	Summary auditSummary

	// TSFindings is the flat list of TypeScript consumer drift findings
	// (case-flips, snake_case wrappers, snake_case params) produced by
	// the TS consumer auditor. Sorted by (file, line, key) for
	// deterministic output. Empty when no TS consumer trees are provided.
	TSFindings []TSFinding
}

ConsumerAuditResult is the output of RunConsumerAudit.

func RunConsumerAudit added in v1.0.7

func RunConsumerAudit(opts ConsumerAuditOptions) (*ConsumerAuditResult, error)

RunConsumerAudit is the single entry point for the consumer audit pipeline.

type ConsumerAuditRow added in v1.0.7

type ConsumerAuditRow struct {
	Category            string
	SubCategory         string
	Endpoint            string
	Method              string
	EndpointStatus      string
	XAnnotated          string
	SchemaDrivenMeshery string
	SchemaDrivenCloud   string
	SchemaCompleteness  string
	PathDrift           string
	Notes               string
	// ChangeLog is the UTC timestamp of the last state transition
	// (new / changed) for this row, in format "YYYY-MM-DD HH:MM:SS".
	// Empty on rows that have never been touched by reconciliation.
	ChangeLog string
}

ConsumerAuditRow is one row of the audit output.

type DeletionRecord added in v1.0.7

type DeletionRecord struct {
	Endpoint  string
	Method    string
	RemovedAt string
}

DeletionRecord is one endpoint removed from the current audit run.

type EndpointState added in v1.0.7

type EndpointState int

EndpointState enumerates the reconciliation states a live audit row can be in.

const (
	StateNew EndpointState = iota
	StateExisting
	StateChanged
)

type Severity

type Severity int

Severity classifies a violation as blocking or advisory.

const (
	// SeverityBlocking causes the validator to exit non-zero.
	SeverityBlocking Severity = iota
	// SeverityAdvisory is reported but does not cause a non-zero exit.
	SeverityAdvisory
)

func (Severity) String

func (s Severity) String() string

type TSConsumerRepo added in v1.1.0

type TSConsumerRepo string

TSConsumerRepo identifies a TypeScript consumer repository.

const (
	// TSConsumerMeshery is meshery/meshery's ui/rtk-query tree.
	TSConsumerMeshery TSConsumerRepo = "meshery"
	// TSConsumerCloud is layer5io/meshery-cloud's ui/api + ui/rtk-query trees.
	TSConsumerCloud TSConsumerRepo = "meshery-cloud"
	// TSConsumerExtensions is layer5labs/meshery-extensions' meshmap/src/rtk-query tree.
	TSConsumerExtensions TSConsumerRepo = "meshery-extensions"
)

type TSFinding added in v1.1.0

type TSFinding struct {
	Repo     TSConsumerRepo
	File     string // repo-relative path, forward slashes
	Line     int    // 1-based source line
	Endpoint string // RTK endpoint name, e.g. "getWorkspaceForCatalog"
	URL      string // URL template extracted from the `url` property
	Method   string // HTTP method (upper-case)
	Kind     TSFindingKind
	Key      string // the offending wire key (e.g. "orgID", "pattern_data")
	Message  string // human-readable description
}

TSFinding is one drift observation produced by the TypeScript consumer auditor. It carries enough context (file:line, repo, endpoint, wire key) for a downstream tool or CI report to point a reviewer at the exact site.

func (TSFinding) String added in v1.1.0

func (f TSFinding) String() string

String renders the finding in a compact, deterministic form suitable for terminal output and baseline files.

type TSFindingKind added in v1.1.0

type TSFindingKind string

TSFindingKind enumerates the classes of drift that the TS consumer flags. These are advisory signals — they do not fail CI directly, but the audit surface makes them visible so Phase 2/3 migration work can target them.

const (
	// TSFindingCaseFlip marks a param/body site that translates a
	// camelCase query-arg into a non-camelCase wire key
	// (e.g. `orgID: queryArg.orgId`). The schema contract is camelCase;
	// the case-flip undoes that.
	TSFindingCaseFlip TSFindingKind = "case-flip"

	// TSFindingSnakeCaseWrapper marks a body wrapper whose top-level key is
	// snake_case (`pattern_data`, `k8s_manifest`). These wrappers predate the
	// identifier-naming migration contract.
	TSFindingSnakeCaseWrapper TSFindingKind = "snake-case-wrapper"

	// TSFindingSnakeCaseParam marks a params object whose key is snake_case
	// (e.g. `page_size`, `total_count` used outside the reserved pagination
	// envelope).
	TSFindingSnakeCaseParam TSFindingKind = "snake-case-param"
)

type TrackedEndpoint added in v1.0.7

type TrackedEndpoint struct {
	Row   ConsumerAuditRow
	State EndpointState
	// Prev is the row as it appeared on the previous run. Populated only
	// when State == StateChanged, so the CLI can render before/after diffs.
	Prev *ConsumerAuditRow
}

TrackedEndpoint is one reconciled row with state transition. The CLI consumes this to render the diff section.

type Violation

type Violation struct {
	// File is the path to the file containing the violation, relative to the
	// repository root.
	File string

	// Message describes the violation in human-readable form.
	Message string

	// Severity indicates whether this violation is blocking or advisory.
	Severity Severity

	// RuleNumber is the rule that triggered this violation (1–41+).
	RuleNumber int
}

Violation is a single schema design issue found during auditing.

func (Violation) String

func (v Violation) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL