Documentation ¶
Index ¶
- Constants
- Variables
- func AlwaysInvalid(_ wrp.Message) error
- func AlwaysValid(_ wrp.Message) error
- func Destination(m wrp.Message) error
- func MessageType(m wrp.Message) error
- func SimpleEventType(m wrp.Message) error
- func SimpleResponseRequestType(m wrp.Message) error
- func Source(m wrp.Message) error
- func Spans(m wrp.Message) error
- func UTF8(m wrp.Message) error
- type MetaValidator
- func (v *MetaValidator) AddMetric(tf *touchstone.Factory, labelNames ...string) error
- func (v MetaValidator) Disabled() bool
- func (v MetaValidator) IsEmpty() bool
- func (v MetaValidator) IsValid() bool
- func (v MetaValidator) Level() validatorLevel
- func (v MetaValidator) Type() validatorType
- func (v *MetaValidator) UnmarshalJSON(b []byte) error
- func (v MetaValidator) Validate(m wrp.Message, ls prometheus.Labels) error
- type Metadata
- type TypeValidator
- type Validator
- type ValidatorError
- type ValidatorFunc
- func NewAlwaysInvalidWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
- func NewAlwaysValidWithMetric(_ *touchstone.Factory, _ ...string) (ValidatorFunc, error)
- func NewDestinationWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
- func NewMessageTypeWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
- func NewSimpleEventTypeWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
- func NewSimpleResponseRequestTypeWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
- func NewSourceWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
- func NewSpansWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
- func NewUTF8WithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
- func NewValidatorWithoutMetric(v func(wrp.Message) error) ValidatorFunc
- type Validators
Examples ¶
Constants ¶
const ( PartnerIDLabel = "partner_id" MessageTypeLabel = "message_type" ClientIDLabel = "client_id" )
Metric label names
const ( UnknownLevel validatorLevel = iota InfoLevel WarningLevel ErrorLevel )
const ( UnknownType validatorType = iota AlwaysInvalidType AlwaysValidType UTF8Type MessageTypeType SourceType DestinationType SimpleResponseRequestTypeType SimpleEventTypeType SpansType )
Variables ¶
var ( ErrorNotSimpleResponseRequestType = NewValidatorError(errors.New("not simple response request message type"), "", []string{"Type"}) ErrorNotSimpleEventType = NewValidatorError(errors.New("not simple event message type"), "", []string{"Type"}) ErrorInvalidSpanLength = NewValidatorError(errors.New("invalid span length"), "", []string{"Spans"}) ErrorInvalidSpanFormat = NewValidatorError(errors.New("invalid span format"), "", []string{"Spans"}) )
var ( ErrValidatorUnmarshalling = errors.New("unmarshalling error") ErrValidatorAddMetric = errors.New("add metric middleware error") ErrValidatorInvalidConfig = errors.New("invalid configuration error") )
var ( ErrorInvalidMessageEncoding = NewValidatorError(errors.New("invalid message encoding"), "", nil) ErrorInvalidMessageType = NewValidatorError(errors.New("invalid message type"), "", []string{"Type"}) ErrorInvalidSource = NewValidatorError(errors.New("invalid Source name"), "", []string{"Source"}) ErrorInvalidDestination = NewValidatorError(errors.New("invalid Destination name"), "", []string{"Destination"}) )
var ( ErrorInvalidValidator = NewValidatorError(errors.New("invalid WRP message type validator"), "", nil) ErrorInvalidMsgType = NewValidatorError(errors.New("invalid WRP message type"), "", []string{"Type"}) ErrorInvalidValidatorError = errors.New("empty ValidatorError 'Err' and 'Message'") )
Functions ¶
func AlwaysInvalid ¶
func AlwaysInvalid(_ wrp.Message) error
AlwaysInvalid doesn't validate anything about the message and always returns an error.
func AlwaysValid ¶
func AlwaysValid(_ wrp.Message) error
AlwaysValid doesn't validate anything about the message and always returns nil.
func Destination ¶ added in v3.4.0
func Destination(m wrp.Message) error
Destination takes messages and validates their Destination. Only mac and uuid destinations are validated. Serial, event and dns destinations are not validated.
func MessageType ¶ added in v3.4.0
func MessageType(m wrp.Message) error
MessageType takes messages and validates their Type.
func SimpleEventType ¶ added in v3.4.0
func SimpleEventType(m wrp.Message) error
SimpleEventType takes messages and validates their Type is of SimpleEventMessageType.
func SimpleResponseRequestType ¶ added in v3.4.0
func SimpleResponseRequestType(m wrp.Message) error
SimpleResponseRequestType takes messages and validates their Type is of SimpleRequestResponseMessageType.
func Source ¶ added in v3.4.0
func Source(m wrp.Message) error
Source takes messages and validates their Source. Only mac and uuid sources are validated. Serial, event and dns sources are not validated.
Types ¶
type MetaValidator ¶ added in v3.4.0
type MetaValidator struct {
// contains filtered or unexported fields
}
MetaValidator wraps validators with additional metadata related functionalities.
Example ¶
var valMeta []MetaValidator valConfig := []byte(`[ { "type": "utf8", "level": "warning" }, { "type": "source", "level": "error" }, { "type": "msg_type", "level": "error", "disable": true } ]`) // Initialize wrp validators if err := json.Unmarshal(valConfig, &valMeta); err != nil { panic(err) } cfg := touchstone.Config{ DefaultNamespace: "n", DefaultSubsystem: "s", } _, pr, err := touchstone.New(cfg) if err != nil { panic(err) } // (Optional) Add metrics to wrp validator labelNames := []string{"label1", "label2"} tf := touchstone.NewFactory(cfg, sallust.Default(), pr) for _, v := range valMeta { if err := v.AddMetric(tf, labelNames...); err != nil { panic(err) } } var ( expectedStatus int64 = 3471 expectedRequestDeliveryResponse int64 = 34 expectedIncludeSpans bool = true ) failurMsg := wrp.Message{ Type: wrp.SimpleEventMessageType, // Missing scheme Source: "external.com", // Invalid Mac Destination: "MAC:+++BB-44-55", TransactionUUID: "DEADBEEF", ContentType: "ContentType", Accept: "Accept", Status: &expectedStatus, RequestDeliveryResponse: &expectedRequestDeliveryResponse, Headers: []string{"Header1", "Header2"}, Metadata: map[string]string{"name": "value"}, Spans: [][]string{{"1", "2"}, {"3"}}, IncludeSpans: &expectedIncludeSpans, Path: "/some/where/over/the/rainbow", Payload: []byte{1, 2, 3, 4}, ServiceName: "ServiceName", PartnerIDs: []string{"foo"}, SessionID: "sessionID123", } l := prometheus.Labels{"label1": "foo", "label2": "bar"} for _, v := range valMeta { err := v.Validate(failurMsg, l) if err == nil { continue } switch v.meta.Level { case WarningLevel: fmt.Printf("%s warnings: %s", v.Type(), err) case ErrorLevel: fmt.Printf("%s errors: %s", v.Type(), err) } }
Output: source errors: validator `source`: Validator error [Source] err=invalid Source name 'external.com': invalid locator
func (*MetaValidator) AddMetric ¶ added in v3.4.0
func (v *MetaValidator) AddMetric(tf *touchstone.Factory, labelNames ...string) error
AddMetric adds a metric middleware to the wrapped validator. Calling `AddMetric` more than once will return an error.
func (MetaValidator) Disabled ¶ added in v3.4.0
func (v MetaValidator) Disabled() bool
Disabled returns whether a validator is disabled.
func (MetaValidator) IsEmpty ¶ added in v3.4.0
func (v MetaValidator) IsEmpty() bool
Empty returns true if the wrapped validator is nil or its metadata are consider empty, otherwise false is returned.
func (MetaValidator) IsValid ¶ added in v3.4.0
func (v MetaValidator) IsValid() bool
IsValid returns true if the wrapped validator and its metadata are valid, otherwise false is returned.
func (MetaValidator) Level ¶ added in v3.4.0
func (v MetaValidator) Level() validatorLevel
Level returns the level of the validator.
func (MetaValidator) Type ¶ added in v3.4.0
func (v MetaValidator) Type() validatorType
Type returns the type of the validator.
func (*MetaValidator) UnmarshalJSON ¶ added in v3.4.0
func (v *MetaValidator) UnmarshalJSON(b []byte) error
UnmarshalJSON unmarshals a json into a MetaValidator. By default, a metricless version of the wrapped validator is used. Refer to `AddMetric` to add a metric middleware to the wrapped validator.
func (MetaValidator) Validate ¶ added in v3.4.0
func (v MetaValidator) Validate(m wrp.Message, ls prometheus.Labels) error
Validate executes its own ValidatorFunc receiver and returns the result.
type Metadata ¶ added in v3.4.0
type Metadata struct { // Level denotes the validator's Level and should be used for client side validator error handling. Level validatorLevel `json:"level"` // Type assigns the validator type. Type validatorType `json:"type"` // disable determines whether incoming messages are validate (`diable` is `false`) // or not (`disable` is `true`), metrics for that validator will not be produced if it's disabled. Disable bool `json:"disable"` }
Metadata contains validator specific metadata.
type TypeValidator ¶
type TypeValidator struct {
// contains filtered or unexported fields
}
TypeValidator is a WRP validator that validates based on message type or using the defaultValidator if message type is unfound.
func NewTypeValidator ¶
func NewTypeValidator(m map[wrp.MessageType]Validator, defaultValidator Validator, tf *touchstone.Factory, labelNames ...string) (TypeValidator, error)
NewTypeValidator is a TypeValidator factory.
Example ¶
cfg := touchstone.Config{ DefaultNamespace: "n", DefaultSubsystem: "s", } _, pr, err := touchstone.New(cfg) tf := touchstone.NewFactory(cfg, sallust.Default(), pr) ai, err := NewAlwaysInvalidWithMetric(tf) if err != nil { panic(err) } av, err := NewAlwaysValidWithMetric(tf) if err != nil { panic(err) } msgv, err := NewTypeValidator( // Validates found msg types map[wrp.MessageType]Validator{wrp.SimpleEventMessageType: av}, // Validates unfound msg types ai, tf) fmt.Printf("%v %T", err == nil, msgv)
Output: true wrpvalidator.TypeValidator
func (TypeValidator) Validate ¶
func (tv TypeValidator) Validate(m wrp.Message, ls prometheus.Labels) error
Validate validates messages based on message type or using the defaultValidator if message type is unfound.
Example ¶
cfg := touchstone.Config{ DefaultNamespace: "n", DefaultSubsystem: "s", } _, pr, err := touchstone.New(cfg) tf := touchstone.NewFactory(cfg, sallust.Default(), pr) ai, err := NewAlwaysInvalidWithMetric(tf) if err != nil { panic(err) } av, err := NewAlwaysValidWithMetric(tf) if err != nil { panic(err) } msgv, err := NewTypeValidator( // Validates found msg types map[wrp.MessageType]Validator{wrp.SimpleEventMessageType: av}, // Validates unfound msg types ai, tf) if err != nil { return } foundErr := msgv.Validate(wrp.Message{Type: wrp.SimpleEventMessageType}, prometheus.Labels{}) // Found success unfoundErr := msgv.Validate(wrp.Message{Type: wrp.CreateMessageType}, prometheus.Labels{}) // Unfound error fmt.Println(foundErr == nil, unfoundErr == nil)
Output: true false
Example (SimpleTypesValidators) ¶
cfg := touchstone.Config{ DefaultNamespace: "n", DefaultSubsystem: "s", } _, pr, err := touchstone.New(cfg) if err != nil { panic(err) } tf := touchstone.NewFactory(cfg, sallust.Default(), pr) sev, err := SimpleEvent(tf) if err != nil { panic(err) } _, pr2, err := touchstone.New(cfg) if err != nil { panic(err) } f2 := touchstone.NewFactory(cfg, sallust.Default(), pr2) srv, err := SimpleResponseRequest(f2) if err != nil { panic(err) } aiv, err := NewAlwaysInvalidWithMetric(tf) if err != nil { panic(err) } msgv, err := NewTypeValidator( // Validates found msg types map[wrp.MessageType]Validator{ wrp.SimpleEventMessageType: sev, wrp.SimpleRequestResponseMessageType: srv, }, // Validates unfound msg types aiv, tf) if err != nil { return } var ( expectedStatus int64 = 3471 expectedRequestDeliveryResponse int64 = 34 expectedIncludeSpans bool = true ) foundErrFailure := msgv.Validate(wrp.Message{ Type: wrp.SimpleRequestResponseMessageType, // Missing scheme Source: "external.com", // Invalid Mac Destination: "MAC:+++BB-44-55", TransactionUUID: "DEADBEEF", ContentType: "ContentType", Accept: "Accept", Status: &expectedStatus, RequestDeliveryResponse: &expectedRequestDeliveryResponse, Headers: []string{"Header1", "Header2"}, Metadata: map[string]string{"name": "value"}, Spans: [][]string{ // // Invalid length {}, // Invalid length {"3"}, // Invalid 'start time', 'duration' and 'status' components {"parent", "name", "not start time", "not duration", "not status"}, // Invalid 'parent' and 'name' components {"1234", "1234", "1234", "1234", "1234"}, }, IncludeSpans: &expectedIncludeSpans, Path: "/some/where/over/the/rainbow", Payload: []byte{1, 2, 3, 4, 0xff, 0xce}, ServiceName: "ServiceName", // Not UFT8 URL string URL: "someURL\xed\xbf\xbf.com", PartnerIDs: []string{"foo"}, SessionID: "sessionID123", }, prometheus.Labels{}) // Found error foundErrSuccess1 := msgv.Validate(wrp.Message{ Type: wrp.SimpleRequestResponseMessageType, Source: "MAC:11:22:33:44:55:66", Destination: "MAC:11:22:33:44:55:61", }, prometheus.Labels{}) // Found success foundErrSuccess2 := msgv.Validate(wrp.Message{ Type: wrp.SimpleEventMessageType, Source: "MAC:11:22:33:44:55:66", // Invalid Destination Destination: "invalid:a-BB-44-55", }, prometheus.Labels{}) // Found error unfoundErrFailure := msgv.Validate(wrp.Message{Type: wrp.CreateMessageType}, prometheus.Labels{}) // Unfound error fmt.Println(foundErrFailure == nil, foundErrSuccess1 == nil, foundErrSuccess2 == nil, unfoundErrFailure == nil)
Output: false true false false
Example (SpecValidators) ¶
cfg := touchstone.Config{ DefaultNamespace: "n", DefaultSubsystem: "s", } _, pr, err := touchstone.New(cfg) if err != nil { panic(err) } tf := touchstone.NewFactory(cfg, sallust.Default(), pr) specv, err := SpecWithMetrics(tf) if err != nil { panic(err) } _, pr2, err := touchstone.New(cfg) if err != nil { panic(err) } f2 := touchstone.NewFactory(cfg, sallust.Default(), pr2) sv, err := NewSourceWithMetric(f2) if err != nil { panic(err) } ai, err := NewAlwaysInvalidWithMetric(tf) if err != nil { panic(err) } msgv, err := NewTypeValidator( // Validates found msg types map[wrp.MessageType]Validator{ // Validates opinionated portions of the spec wrp.SimpleEventMessageType: specv, // Only validates Source and nothing else wrp.SimpleRequestResponseMessageType: sv, }, // Validates unfound msg types ai, tf) if err != nil { return } var ( expectedStatus int64 = 3471 expectedRequestDeliveryResponse int64 = 34 expectedIncludeSpans bool = true ) foundErrFailure := msgv.Validate(wrp.Message{ Type: wrp.SimpleEventMessageType, // Missing scheme Source: "external.com", // Invalid Mac Destination: "MAC:+++BB-44-55", TransactionUUID: "DEADBEEF", ContentType: "ContentType", Accept: "Accept", Status: &expectedStatus, RequestDeliveryResponse: &expectedRequestDeliveryResponse, Headers: []string{"Header1", "Header2"}, Metadata: map[string]string{"name": "value"}, Spans: [][]string{{"1", "2"}, {"3"}}, IncludeSpans: &expectedIncludeSpans, Path: "/some/where/over/the/rainbow", // Not UFT8 Payload Payload: []byte{1, 2, 3, 4, 0xff /* \xed\xbf\xbf is invalid */, 0xce}, ServiceName: "ServiceName", // Not UFT8 URL string URL: "someURL\xed\xbf\xbf.com", PartnerIDs: []string{"foo"}, SessionID: "sessionID123", }, prometheus.Labels{}) // Found error foundErrSuccess1 := msgv.Validate(wrp.Message{ Type: wrp.SimpleEventMessageType, Source: "MAC:11:22:33:44:55:66", Destination: "MAC:11:22:33:44:55:61", }, prometheus.Labels{}) // Found success foundErrSuccess2 := msgv.Validate(wrp.Message{ Type: wrp.SimpleRequestResponseMessageType, Source: "MAC:11:22:33:44:55:66", Destination: "invalid:a-BB-44-55", }, prometheus.Labels{}) // Found success unfoundErrFailure := msgv.Validate(wrp.Message{Type: wrp.CreateMessageType}, prometheus.Labels{}) // Unfound error fmt.Println(foundErrFailure == nil, foundErrSuccess1 == nil, foundErrSuccess2 == nil, unfoundErrFailure == nil)
Output: false true true false
type Validator ¶
type Validator interface {
Validate(wrp.Message, prometheus.Labels) error
}
Validator is a WRP validator that allows access to the Validate function.
type ValidatorError ¶
type ValidatorError struct { // Err is the cause of the error, e.g. invalid message type. // Either Err or Message must be set and nonempty Err error // Message is a validation message in case the validator wants // to communicate something beyond the Err cause. Message string // Fields are the relevant fields involved in Err. Fields []string }
func NewValidatorError ¶
func NewValidatorError(err error, m string, f []string) ValidatorError
NewValidatorError is a ValidatorError factory and will panic if both 'err' and 'm' are empty or nil
func (ValidatorError) Error ¶
func (ve ValidatorError) Error() string
func (ValidatorError) Unwrap ¶
func (ve ValidatorError) Unwrap() error
Unwrap returns the ValidatorError's Error
type ValidatorFunc ¶
type ValidatorFunc func(wrp.Message, prometheus.Labels) error
ValidatorFunc is a WRP validator that takes messages and validates them against functions.
func NewAlwaysInvalidWithMetric ¶ added in v3.4.0
func NewAlwaysInvalidWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
NewAlwaysInvalidWithMetric returns a AlwaysInvalid validator with a metric middleware.
func NewAlwaysValidWithMetric ¶ added in v3.4.0
func NewAlwaysValidWithMetric(_ *touchstone.Factory, _ ...string) (ValidatorFunc, error)
NewAlwaysValidWithMetric returns a AlwaysValid validator with a stubbed metric middleware (no metric produced).
func NewDestinationWithMetric ¶ added in v3.4.0
func NewDestinationWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
NewDestinationWithMetric returns a Destination validator with a metric middleware.
func NewMessageTypeWithMetric ¶ added in v3.4.0
func NewMessageTypeWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
NewMessageTypeWithMetric returns a MessageType validator with a metric middleware.
func NewSimpleEventTypeWithMetric ¶ added in v3.4.0
func NewSimpleEventTypeWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
NewSimpleEventTypeWithMetric returns a SimpleEventType validator with a metric middleware.
func NewSimpleResponseRequestTypeWithMetric ¶ added in v3.4.0
func NewSimpleResponseRequestTypeWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
NewSimpleResponseRequestTypeWithMetric returns a SimpleResponseRequestType validator with a metric middleware.
func NewSourceWithMetric ¶ added in v3.4.0
func NewSourceWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
NewSourceWithMetric returns a Source validator with a metric middleware.
func NewSpansWithMetric ¶ added in v3.4.0
func NewSpansWithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
NewSpansWithMetric returns a Spans validator with a metric middleware.
func NewUTF8WithMetric ¶ added in v3.4.0
func NewUTF8WithMetric(tf *touchstone.Factory, labelNames ...string) (ValidatorFunc, error)
NewUTF8WithMetric returns a UTF8 validator with a metric middleware.
func NewValidatorWithoutMetric ¶ added in v3.4.0
func NewValidatorWithoutMetric(v func(wrp.Message) error) ValidatorFunc
NewValidatorWithoutMetric returns a validator `v` with a stubbed metric middleware (no metric required or produced).
func (ValidatorFunc) Validate ¶
func (vf ValidatorFunc) Validate(m wrp.Message, ls prometheus.Labels) error
Validate executes its own ValidatorFunc receiver and returns the result.
type Validators ¶
type Validators []Validator
Validators is a WRP validator that ensures messages are valid based on message type and each validator in the list.
func SimpleEvent ¶ added in v3.4.0
func SimpleEvent(tf *touchstone.Factory, labelNames ...string) (Validators, error)
SimpleEvent ensures messages are valid based on each validator in the list. SimpleEvent validates the following: UTF8 (all string fields), MessageType is valid, Source, Destination, MessageType is of SimpleEventMessageType.
func SimpleResponseRequest ¶ added in v3.4.0
func SimpleResponseRequest(tf *touchstone.Factory, labelNames ...string) (Validators, error)
SimpleResponseRequest ensures messages are valid based on each validator in the list. SimpleResponseRequest validates the following: UTF8 (all string fields), MessageType is valid, Source, Destination, Spans, MessageType is of SimpleRequestResponseMessageType.
func SpecWithMetrics ¶ added in v3.4.0
func SpecWithMetrics(tf *touchstone.Factory, labelNames ...string) (Validators, error)
SpecWithMetrics ensures messages are valid based on each spec validator in the list. Only validates the opinionated portions of the spec. SpecWithMetrics validates the following fields: UTF8 (all string fields), MessageType, Source, Destination
func (Validators) Add ¶
func (vs Validators) Add(v ...Validator) Validators
Add returns a new Validators with the appended Validator list
func (Validators) AddFunc ¶
func (vs Validators) AddFunc(vf ...ValidatorFunc) Validators
AddFunc returns a new Validators with the appended ValidatorFunc list
func (Validators) Validate ¶
func (vs Validators) Validate(m wrp.Message, ls prometheus.Labels) error
Validate runs messages through each validator in the validators list. It returns as soon as the message is considered invalid, otherwise returns nil if valid.