wrp

package module
v3.5.2 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: Apache-2.0 Imports: 15 Imported by: 36

README

wrp-go

wrp-go provides a library implementing the Web Routing Protocol structures and supporting utilities.

Build Status codecov.io Go Report Card Quality Gate Status Apache V2 License GitHub Release GoDoc

Table of Contents

Code of Conduct

This project and everyone participating in it are governed by the XMiDT Code Of Conduct. By participating, you agree to this Code.

Validators

To setup application wrp validators, visit the example ExampleMetaValidator GoDoc.

Application config example:

# wrpValidators defines the wrp validators used to validate incoming wrp messages.
# (Optional)
# Available validator types: always_invalid, always_valid, utf8, msg_type, source, destination, simple_res_req, simple_event, spans
# Available validator levels: info, warning, error
# Validators can be disabled with `disable: true`, it is false by default
wrpValidators:
  - type: utf8
    level: warning
    disable: true
  - type: source
    level: error

Examples

To use the wrp-go library, it first should be added as an import in the file you plan to use it. Examples can be found at the top of the GoDoc.

Contributing

Refer to CONTRIBUTING.md.

Documentation

Overview

Package wrp defines the various WRP messages supported by WebPA and implements serialization for those messages.

Some common uses of this package include:

(1) Encoding a specific message to send to a WebPA server:

var (
	// the infrastructure automatically fills in the correct Type field
	message = SimpleRequestResponse{
		Source: "myserver.com",
		Destination: "mac:112233445566",
		Payload: []byte("here is a lovely little payload that the device understands"),
	}

	buffer bytes.Buffer
	encoder = NewEncoder(&buffer, Msgpack)
)

if err := encoder.Encode(&message); err != nil {
	// deal with the error
}

(2) Decoding any generic WRP message, perhaps sent by a client:

// encoded may also be an io.Reader if desired
func myHandler(encoded []byte) (message *Message, err error) {
	decoder := NewDecoderBytes(encoded, Msgpack)
	message = new(Message)
	err = decoder.Decode(message)
	return
}

(3) Transcoding messages from one format to another:

// assume source contains a JSON message
func jsonToMsgpack(source io.Reader) ([]byte, error) {
	var (
		decoder = NewDecoder(source, JSON)
		buffer bytes.Buffer
		encoder = NewEncoder(&buffer, Msgpack)
	)

	// TranscodeMessage returns a *Message as its first value, which contains
	// the generic WRP message data
	if _, err := TranscodeMessage(encoder, decoder); err != nil {
		return nil, err
	}

	return buffer.Bytes(), nil
}

(4) Pooling encoders and/or decoders for efficiency:

// transcoding, using pools:
var (
	decoderPool = NewDecoderPool(100, JSON)
	encoderPool = NewEncoderPool(100, Msgpack)
)

func jsonToMsgpackUsingPools(source io.Reader) ([]byte, error) {
	var (
		decoder = decoderPool.Get()
		buffer bytes.Buffer
		encoder = encoderPool.Get()
	)

	defer decoderPool.Put(decoder)
	defer encoderPool.Put(encoder)

	// TranscodeMessage returns a *Message as its first value, which contains
	// the generic WRP message data
	if _, err := TranscodeMessage(encoder, decoder); err != nil {
		return nil, err
	}

	return buffer.Bytes(), nil
}

Index

Constants

View Source
const (
	Msgpack Format = iota
	JSON

	MimeTypeMsgpack     = "application/msgpack"
	MimeTypeJson        = "application/json"
	MimeTypeOctetStream = "application/octet-stream"

	// Deprecated: This constant should only be used for backwards compatibility
	// matching.  Use MimeTypeMsgpack instead.
	MimeTypeWrp = "application/wrp"
)
View Source
const (
	SchemeMAC     = "mac"
	SchemeUUID    = "uuid"
	SchemeDNS     = "dns"
	SchemeSerial  = "serial"
	SchemeSelf    = "self"
	SchemeEvent   = "event"
	SchemeUnknown = ""
)

Variables

View Source
var (
	ErrorInvalidDeviceName = errors.New("invalid device name")
	ErrorInvalidLocator    = errors.New("invalid locator")

	// DevicIDPattern is the precompiled regular expression that all device identifiers must match.
	// Matching is partial, as everything after the service is ignored.
	DeviceIDPattern = regexp.MustCompile(
		`^(?P<prefix>(?i)mac|uuid|dns|serial|self):(?P<id>[^/]+)(?P<service>/[^/]+)?`,
	)

	// LocatorPattern is the precompiled regular expression that all locators must match.
	LocatorPattern = regexp.MustCompile(
		`^(?P<scheme>(?i)mac|uuid|dns|serial|event|self):(?P<authority>[^/]+)?(?P<service>/[^/]+)?(?P<ignored>.+)?`,
	)
)
View Source
var (
	ErrInvalidMessageType = errors.New("invalid message type")
	ErrInvalidPartnerID   = errors.New("invalid partner ID")
	ErrInvalidSource      = errors.New("invalid source locator")
	ErrInvalidDest        = errors.New("invalid destination locator")
	ErrInvalidString      = errors.New("invalid UTF-8 string")
)
View Source
var (
	ErrNotUTF8        = errors.New("field contains non-utf-8 characters")
	ErrUnexpectedKind = errors.New("a struct or non-nil pointer to struct is required")
)

Functions

func MustEncode

func MustEncode(message interface{}, f Format) []byte

MustEncode is a convenience function that attempts to encode a given message. A panic is raised on any error. This function is handy for package initialization.

func UTF8 added in v3.1.3

func UTF8(v interface{}) error

UTF8 takes any struct verifies that it contains UTF-8 strings.

Types

type CRUD deprecated

type CRUD struct {
	Type                    MessageType       `json:"msg_type"`
	Source                  string            `json:"source"`
	Destination             string            `json:"dest"`
	TransactionUUID         string            `json:"transaction_uuid,omitempty"`
	ContentType             string            `json:"content_type,omitempty"`
	Headers                 []string          `json:"headers,omitempty"`
	Metadata                map[string]string `json:"metadata,omitempty"`
	Spans                   [][]string        `json:"spans,omitempty"`
	IncludeSpans            *bool             `json:"include_spans,omitempty"`
	Status                  *int64            `json:"status,omitempty"`
	RequestDeliveryResponse *int64            `json:"rdr,omitempty"`
	Path                    string            `json:"path"`
	Payload                 []byte            `json:"payload,omitempty"`
	PartnerIDs              []string          `json:"partner_ids,omitempty"`
}

CRUD represents a WRP message of one of the CRUD message types. This type does not implement BeforeEncode, and so does not automatically set the Type field. Client code must set the Type code appropriately.

https://github.com/xmidt-org/wrp-c/wiki/Web-Routing-Protocol#crud-message-definition

Deprecated: A future version of wrp will remove this type.

func (*CRUD) CodecDecodeSelf

func (x *CRUD) CodecDecodeSelf(d *codec1978.Decoder)

func (*CRUD) CodecEncodeSelf

func (x *CRUD) CodecEncodeSelf(e *codec1978.Encoder)

func (*CRUD) From

func (msg *CRUD) From() string

func (*CRUD) IsCodecEmpty added in v3.1.0

func (x *CRUD) IsCodecEmpty() bool

func (*CRUD) IsTransactionPart

func (msg *CRUD) IsTransactionPart() bool

func (*CRUD) MessageType

func (msg *CRUD) MessageType() MessageType

func (*CRUD) Response

func (msg *CRUD) Response(newSource string, requestDeliveryResponse int64) Routable

func (*CRUD) SetIncludeSpans

func (msg *CRUD) SetIncludeSpans(value bool) *CRUD

SetIncludeSpans simplifies setting the optional IncludeSpans field, which is a pointer type tagged with omitempty.

func (*CRUD) SetRequestDeliveryResponse

func (msg *CRUD) SetRequestDeliveryResponse(value int64) *CRUD

SetRequestDeliveryResponse simplifies setting the optional RequestDeliveryResponse field, which is a pointer type tagged with omitempty.

func (*CRUD) SetStatus

func (msg *CRUD) SetStatus(value int64) *CRUD

SetStatus simplifies setting the optional Status field, which is a pointer type tagged with omitempty.

func (*CRUD) To

func (msg *CRUD) To() string

func (*CRUD) TransactionKey

func (msg *CRUD) TransactionKey() string

type Decoder

type Decoder interface {
	Decode(interface{}) error
	Reset(io.Reader)
	ResetBytes([]byte)
}

Decoder represents the underlying ugorji behavior that WRP supports

func NewDecoder

func NewDecoder(input io.Reader, f Format) Decoder

NewDecoder produces a ugorji Decoder using the appropriate WRP configuration for the given format

func NewDecoderBytes

func NewDecoderBytes(input []byte, f Format) Decoder

NewDecoderBytes produces a ugorji Decoder using the appropriate WRP configuration for the given format

type DeviceID added in v3.1.2

type DeviceID string

ID represents a normalized identifier for a device.

func ParseDeviceID added in v3.1.2

func ParseDeviceID(deviceName string) (DeviceID, error)

ParseID parses a raw device name into a canonicalized identifier.

func (DeviceID) Bytes added in v3.1.2

func (id DeviceID) Bytes() []byte

Bytes is a convenience function to obtain the []byte representation of an ID.

func (DeviceID) ID added in v3.2.0

func (id DeviceID) ID() string

ID is a convenience function to obtain the string representation of the identifier portion of the ID.

func (DeviceID) Prefix added in v3.2.0

func (id DeviceID) Prefix() string

String is a convenience function to obtain the string representation of the prefix portion of the ID.

type EncodeListener

type EncodeListener interface {
	BeforeEncode() error
}

EncodeListener can be implemented on any type passed to an Encoder in order to get notified when an encoding happens. This interface is useful to set mandatory fields, such as message type.

type Encoder

type Encoder interface {
	Encode(interface{}) error
	Reset(io.Writer)
	ResetBytes(*[]byte)
}

Encoder represents the underlying ugorji behavior that WRP supports

func NewEncoder

func NewEncoder(output io.Writer, f Format) Encoder

NewEncoder produces a ugorji Encoder using the appropriate WRP configuration for the given format

func NewEncoderBytes

func NewEncoderBytes(output *[]byte, f Format) Encoder

NewEncoderBytes produces a ugorji Encoder using the appropriate WRP configuration for the given format

type Format

type Format int

Format indicates which format is desired. The zero value indicates Msgpack, which means by default other infrastructure can assume msgpack-formatted data.

func AllFormats

func AllFormats() []Format

AllFormats returns a distinct slice of all supported formats.

func FormatFromContentType

func FormatFromContentType(contentType string, fallback ...Format) (Format, error)

FormatFromContentType examines the Content-Type value and returns the appropriate Format. This function returns an error if the given Content-Type did not map to a WRP format.

The optional fallback is used if contentType is the empty string. Only the first fallback value is used. The rest are ignored. This approach allows simple usages such as:

FormatFromContentType(header.Get("Content-Type"), wrp.Msgpack)

func (Format) ContentType

func (f Format) ContentType() string

ContentType returns the MIME type associated with this format

func (Format) String

func (i Format) String() string

type Locator added in v3.4.1

type Locator struct {
	// Scheme is the scheme type of the locator.  A CPE will have the forms
	// `mac`, `uuid`, `serial`, `self`.  A server or cloud service will have
	// the form `dns`.  An event locator that is used for pub-sub listeners
	// will have the form `event`.
	//
	// The Scheme MUST NOT be used to determine where to send a message, but
	// rather to determine how to interpret the authority and service.
	//
	// The Scheme value will always be lower case.
	Scheme string

	// Authority is the authority portion of the locator.  For a CPE, this
	// will be the device identifier.  For a server or cloud service, this
	// will be the DNS name of the service.  For an event locator, this will
	// be the event name.
	Authority string

	// Service is the service name portion of the locator.  This is optional
	// and is used to identify which service(s) the message is targeting or
	// originated from.  A Service value will not contain any `/` characters.
	Service string

	// Ignored is an optional portion of the locator that is ignored by the
	// WRP spec, but is provided to consumers for their usage.  The Ignored
	// value will contain a prefix of the `/` character.
	Ignored string

	// ID is the device identifier portion of the locator if it is one.
	ID DeviceID
}

Locator represents a device locator, which is a device identifier an optional service name and an optional ignored portion at the end.

The general format is:

{scheme}:{authority}/{service}/{ignored}

See https://xmidt.io/docs/wrp/basics/#locators for more details.

func ParseLocator added in v3.4.1

func ParseLocator(locator string) (Locator, error)

ParseLocator parses a raw locator string into a canonicalized locator.

func (Locator) HasDeviceID added in v3.4.1

func (l Locator) HasDeviceID() bool

HasDeviceID returns true if the locator is a device identifier.

func (Locator) IsSelf added in v3.4.2

func (l Locator) IsSelf() bool

IsSelf returns true if the locator is a self locator.

func (Locator) String added in v3.4.1

func (l Locator) String() string

type Message

type Message struct {
	// Type is the message type for the message.
	//
	// example: SimpleRequestResponseMessageType
	Type MessageType `json:"msg_type"`

	// Source is the device_id name of the device originating the request or response.
	//
	// example: dns:talaria.xmidt.example.com
	Source string `json:"source,omitempty"`

	// Destination is the device_id name of the target device of the request or response.
	//
	// example: event:device-status/mac:ffffffffdae4/online
	Destination string `json:"dest,omitempty"`

	// TransactionUUID The transaction key for the message
	//
	// example: 546514d4-9cb6-41c9-88ca-ccd4c130c525
	TransactionUUID string `json:"transaction_uuid,omitempty"`

	// ContentType The media type of the payload.
	//
	// example: json
	ContentType string `json:"content_type,omitempty"`

	// Accept is the media type accepted in the response.
	Accept string `json:"accept,omitempty"`

	// Status is the response status from the originating service.
	Status *int64 `json:"status,omitempty"`

	// RequestDeliveryResponse is the request delivery response is the delivery result
	// of the previous (implied request) message with a matching transaction_uuid
	RequestDeliveryResponse *int64 `json:"rdr,omitempty"`

	// Headers is the headers associated with the payload.
	Headers []string `json:"headers,omitempty"`

	// Metadata is the map of name/value pairs used by consumers of WRP messages for filtering & other purposes.
	//
	// example: {"/boot-time":"1542834188","/last-reconnect-reason":"spanish inquisition"}
	Metadata map[string]string `json:"metadata,omitempty"`

	// Spans is an array of arrays of timing values as a list in the format: "parent" (string), "name" (string),
	// "start time" (int), "duration" (int), "status" (int)
	Spans [][]string `json:"spans,omitempty"`

	// IncludeSpans indicates whether timing values should be included in the response.
	//
	// Deprecated: A future version of wrp will remove this field.
	IncludeSpans *bool `json:"include_spans,omitempty"`

	// Path is the path to which to apply the payload.
	Path string `json:"path,omitempty"`

	// Payload is the payload for this message.  It's format is expected to match ContentType.
	//
	// For JSON, this field must be a UTF-8 string.  Binary payloads may be base64-encoded.
	//
	// For msgpack, this field may be raw binary or a UTF-8 string.
	//
	// example: eyJpZCI6IjUiLCJ0cyI6IjIwMTktMDItMTJUMTE6MTA6MDIuNjE0MTkxNzM1WiIsImJ5dGVzLXNlbnQiOjAsIm1lc3NhZ2VzLXNlbnQiOjEsImJ5dGVzLXJlY2VpdmVkIjowLCJtZXNzYWdlcy1yZWNlaXZlZCI6MH0=
	Payload []byte `json:"payload,omitempty"`

	// ServiceName is the originating point of the request or response.
	ServiceName string `json:"service_name,omitempty"`

	// URL is the url to use when connecting to the nanomsg pipeline.
	URL string `json:"url,omitempty"`

	// PartnerIDs is the list of partner ids the message is meant to target.
	//
	// example: ["hello","world"]
	PartnerIDs []string `json:"partner_ids,omitempty"`

	// SessionID is the ID for the current session.
	SessionID string `json:"session_id,omitempty"`

	// QualityOfService is the qos value associated with this message.  Values between 0 and 99, inclusive,
	// are defined by the wrp spec.  Negative values are assumed to be zero, and values larger than 99
	// are assumed to be 99.
	QualityOfService QOSValue `json:"qos"`
}

Message is the union of all WRP fields, made optional (except for Type). This type is useful for transcoding streams, since deserializing from non-msgpack formats like JSON has some undesirable side effects.

IMPORTANT: Anytime a new WRP field is added to any message, or a new message with new fields, those new fields must be added to this struct for transcoding to work properly. And of course: update the tests!

For server code that sends specific messages, use one of the other WRP structs in this package.

For server code that needs to read one format and emit another, use this struct as it allows client code to transcode without knowledge of the exact type of message.

swagger:response Message

func TranscodeMessage

func TranscodeMessage(target Encoder, source Decoder) (msg *Message, err error)

TranscodeMessage converts a WRP message of any type from one format into another, e.g. from JSON into Msgpack. The intermediate, generic Message used to hold decoded values is returned in addition to any error. If a decode error occurs, this function will not perform the encoding step.

func (*Message) CodecDecodeSelf

func (x *Message) CodecDecodeSelf(d *codec1978.Decoder)

func (*Message) CodecEncodeSelf

func (x *Message) CodecEncodeSelf(e *codec1978.Encoder)

func (*Message) FindEventStringSubMatch

func (msg *Message) FindEventStringSubMatch() string

func (*Message) From

func (msg *Message) From() string

func (*Message) IsCodecEmpty added in v3.1.0

func (x *Message) IsCodecEmpty() bool

func (*Message) IsQOSAckPart added in v3.1.4

func (msg *Message) IsQOSAckPart() bool

IsQOSAckPart determines whether or not a message can QOS ack.

func (*Message) IsTransactionPart

func (msg *Message) IsTransactionPart() bool

func (*Message) MessageType

func (msg *Message) MessageType() MessageType

func (*Message) Response

func (msg *Message) Response(newSource string, requestDeliveryResponse int64) Routable

func (*Message) SetIncludeSpans

func (msg *Message) SetIncludeSpans(value bool) *Message

SetIncludeSpans simplifies setting the optional IncludeSpans field, which is a pointer type tagged with omitempty.

func (*Message) SetRequestDeliveryResponse

func (msg *Message) SetRequestDeliveryResponse(value int64) *Message

SetRequestDeliveryResponse simplifies setting the optional RequestDeliveryResponse field, which is a pointer type tagged with omitempty.

func (*Message) SetStatus

func (msg *Message) SetStatus(value int64) *Message

SetStatus simplifies setting the optional Status field, which is a pointer type tagged with omitempty.

func (*Message) To

func (msg *Message) To() string

func (*Message) TransactionKey

func (msg *Message) TransactionKey() string

func (*Message) TrimmedPartnerIDs added in v3.5.0

func (msg *Message) TrimmedPartnerIDs() []string

TrimmedPartnerIDs returns a copy of the PartnerIDs field with all empty strings removed.

type MessageType

type MessageType int64

MessageType indicates the kind of WRP message

const (
	Invalid0MessageType MessageType = iota
	Invalid1MessageType
	AuthorizationMessageType
	SimpleRequestResponseMessageType
	SimpleEventMessageType
	CreateMessageType
	RetrieveMessageType
	UpdateMessageType
	DeleteMessageType
	ServiceRegistrationMessageType
	ServiceAliveMessageType
	UnknownMessageType
	LastMessageType
)

func StringToMessageType

func StringToMessageType(value string) MessageType

StringToMessageType converts a string into an enumerated MessageType constant. If the value equals the friendly name of a type, e.g. "Auth" for AuthMessageType, that type is returned. Otherwise, the value is converted to an integer and looked up, with an error being returned in the event the integer value is not valid.

func (MessageType) FriendlyName

func (mt MessageType) FriendlyName() string

FriendlyName is just the String version of this type minus the "MessageType" suffix. This is used in most textual representations, such as HTTP headers.

func (MessageType) RequiresTransaction added in v3.2.0

func (mt MessageType) RequiresTransaction() bool

RequiresTransaction tests if messages of this type are allowed to participate in transactions. If this method returns false, the TransactionUUID field should be ignored (but passed through where applicable). If this method returns true, TransactionUUID must be included in request.

func (MessageType) String

func (i MessageType) String() string

func (MessageType) SupportsQOSAck added in v3.1.4

func (mt MessageType) SupportsQOSAck() bool

SupportsQOSAck tests if messages of this type are allowed to participate in QOS Ack as specified in https://xmidt.io/docs/wrp/basics/#qos-description-qos . If this method returns false, QOS Ack is foregone.

type Normifier added in v3.5.0

type Normifier struct {
	// contains filtered or unexported fields
}

Normifier applies a series of normalizing options to a WRP message.

func NewNormifier added in v3.5.0

func NewNormifier(opts ...NormifierOption) *Normifier

New creates a new Correctifier with the given options.

func (*Normifier) Normify added in v3.5.0

func (n *Normifier) Normify(m *Message) error

Normify applies the normalizing and validating options to the message. It returns an error if any of the options fail.

type NormifierOption added in v3.5.0

type NormifierOption interface {
	// contains filtered or unexported methods
}

NormifierOption is a functional option for normalizing a WRP message.

func ClampQualityOfService added in v3.5.2

func ClampQualityOfService() NormifierOption

ClampQualityOfService clamps a wrp message's qos value between 0 and 99.

func EnsureMetadataInt64 added in v3.5.0

func EnsureMetadataInt64(key string, i int64) NormifierOption

EnsureMetadataInt64 ensures that the message has the given integer metadata. This will always set the metadata. The integer is converted to a string using base 10.

func EnsureMetadataString added in v3.5.0

func EnsureMetadataString(key, value string) NormifierOption

EnsureMetadataString ensures that the message has the given string metadata. This will always set the metadata.

func EnsureMetadataTime added in v3.5.0

func EnsureMetadataTime(key string, t time.Time) NormifierOption

EnsureMetadataTime ensures that the message has the given time metadata. This will always set the metadata. The time is formatted using RFC3339.

func EnsurePartnerID added in v3.5.0

func EnsurePartnerID(partnerID string) NormifierOption

EnsurePartnerID ensures that the message includes the given partner ID in the list. If not present, the partner ID is added to the list.

func EnsureTransactionUUID added in v3.5.0

func EnsureTransactionUUID() NormifierOption

EnsureTransactionUUID ensures that the message has a transaction UUID. If the message does not have a transaction UUID, a new one is generated and added to the message.

func ReplaceAnySelfLocator added in v3.5.0

func ReplaceAnySelfLocator(me string) NormifierOption

ReplaceAnySelfLocator replaces any `self:` based locator with the scheme and authority of the given locator. If the given locator is not valid, the option returns an error.

func ReplaceDestinationSelfLocator added in v3.5.0

func ReplaceDestinationSelfLocator(me string) NormifierOption

ReplaceDestinationSelfLocator replaces the destination of the message with the given locator if the destination is a `self:` based locator. If the given locator is not valid, the option returns an error.

func ReplaceSourceSelfLocator added in v3.5.0

func ReplaceSourceSelfLocator(me string) NormifierOption

ReplaceSourceSelfLocator replaces a `self:` based source locator with the scheme and authority of the given locator. If the given locator is not valid, the option returns an error.

func SetPartnerID added in v3.5.0

func SetPartnerID(partnerID string) NormifierOption

SetPartnerID ensures that the message has only the given partner ID. This will always set the partner ID, replacing any existing partner IDs.

func SetSessionID added in v3.5.0

func SetSessionID(sessionID string) NormifierOption

SetSessionID ensures that the message has the given session ID. This will always set the session ID, replacing any existing session ID

func ValidateDestination added in v3.5.0

func ValidateDestination() NormifierOption

ValidateDestination ensures that the destination locator is valid.

func ValidateHasPartner added in v3.5.0

func ValidateHasPartner(partners ...string) NormifierOption

ValidateHasPartner ensures that the message has one of the given partner IDs.

func ValidateIsPartner added in v3.5.0

func ValidateIsPartner(partner string) NormifierOption

ValidateIsPartner ensures that the message has the given partner ID.

func ValidateMessageType added in v3.5.0

func ValidateMessageType() NormifierOption

ValidateMessageType ensures that the message type is valid.

func ValidateOnlyUTF8Strings added in v3.5.0

func ValidateOnlyUTF8Strings() NormifierOption

ValidateOnlyUTF8Strings ensures that all string fields in the message are valid UTF-8.

func ValidateSource added in v3.5.0

func ValidateSource() NormifierOption

ValidateSource ensures that the source locator is valid.

type QOSLevel added in v3.1.4

type QOSLevel int

QOSLevel is the quality of service level associated with a WRP message.

const (
	QOSLow      QOSLevel = iota // Low
	QOSMedium                   // Medium
	QOSHigh                     // High
	QOSCritical                 // Critical
)

func (QOSLevel) String added in v3.1.4

func (i QOSLevel) String() string

type QOSValue added in v3.1.4

type QOSValue int

QOSValue is the quality of service value set in a WRP message. Values of this type determine what QOSLevel a message has.

const (
	QOSLowValue QOSValue = iota * 25
	QOSMediumValue
	QOSHighValue
	QOSCriticalValue
)

func (QOSValue) Level added in v3.1.4

func (qv QOSValue) Level() QOSLevel

Level determines the QOSLevel for this value. Negative values are assumed to be QOSLow. Values higher than the highest value (99) are assumed to be QOSCritical.

type Routable

type Routable interface {
	Typed

	// To is the destination of this Routable instance.  It corresponds to the Destination field
	// in WRP messages defined in this package.
	To() string

	// From is the originator of this Routable instance.  It corresponds to the Source field
	// in WRP messages defined in this package.
	From() string

	// IsTransactionPart tests if this message represents part of a transaction.  For this to be true,
	// both (1) the msg_type field must be of a type that participates in transactions and (2) a transaction_uuid
	// must exist in the message (see TransactionKey).
	//
	// If this method returns true, TransactionKey will always return a non-empty string.
	IsTransactionPart() bool

	// TransactionKey corresponds to the transaction_uuid field.  If present, this field is used
	// to match up responses from devices.
	//
	// Not all Routables support transactions, e.g. SimpleEvent.  For those Routable messages that do
	// not possess a transaction_uuid field, this method returns an empty string.
	TransactionKey() string

	// Response produces a new Routable instance which is a response to this one.  The new Routable's
	// destination (From) is set to the original source (To), with the supplied newSource used as the response's source.
	// The requestDeliveryResponse parameter indicates the success or failure of this response.  The underlying
	// type of the returned Routable will be the same as this type, i.e. if this instance is a Message,
	// the returned Routable will also be a Message.
	//
	// If applicable, the response's payload is set to nil.  All other fields are copied as is into the response.
	Response(newSource string, requestDeliveryResponse int64) Routable
}

Routable describes an object which can be routed. Implementations will most often also be WRP Message instances. All Routable objects may be passed to Encoders and Decoders.

Not all WRP messages are Routable. Only messages that can be sent through routing software (e.g. talaria) implement this interface.

type ServiceAlive deprecated

type ServiceAlive struct {
	// Type is exposed principally for encoding.  This field *must* be set to ServiceAliveMessageType,
	// and is automatically set by the BeforeEncode method.
	Type MessageType `json:"msg_type"`
}

ServiceAlive represents a WRP message of type ServiceAliveMessageType.

https://github.com/xmidt-org/wrp-c/wiki/Web-Routing-Protocol#on-device-service-alive-message-definition

Deprecated: A future version of wrp will remove this type.

func (*ServiceAlive) BeforeEncode

func (msg *ServiceAlive) BeforeEncode() error

func (*ServiceAlive) CodecDecodeSelf

func (x *ServiceAlive) CodecDecodeSelf(d *codec1978.Decoder)

func (*ServiceAlive) CodecEncodeSelf

func (x *ServiceAlive) CodecEncodeSelf(e *codec1978.Encoder)

func (*ServiceAlive) IsCodecEmpty added in v3.1.0

func (x *ServiceAlive) IsCodecEmpty() bool

type ServiceRegistration deprecated

type ServiceRegistration struct {
	// Type is exposed principally for encoding.  This field *must* be set to ServiceRegistrationMessageType,
	// and is automatically set by the BeforeEncode method.
	Type        MessageType `json:"msg_type"`
	ServiceName string      `json:"service_name"`
	URL         string      `json:"url"`
}

ServiceRegistration represents a WRP message of type ServiceRegistrationMessageType.

https://github.com/xmidt-org/wrp-c/wiki/Web-Routing-Protocol#on-device-service-registration-message-definition

Deprecated: A future version of wrp will remove this type.

func (*ServiceRegistration) BeforeEncode

func (msg *ServiceRegistration) BeforeEncode() error

func (*ServiceRegistration) CodecDecodeSelf

func (x *ServiceRegistration) CodecDecodeSelf(d *codec1978.Decoder)

func (*ServiceRegistration) CodecEncodeSelf

func (x *ServiceRegistration) CodecEncodeSelf(e *codec1978.Encoder)

func (*ServiceRegistration) IsCodecEmpty added in v3.1.0

func (x *ServiceRegistration) IsCodecEmpty() bool

type SimpleEvent deprecated

type SimpleEvent struct {
	// Type is exposed principally for encoding.  This field *must* be set to SimpleEventMessageType,
	// and is automatically set by the BeforeEncode method.
	Type        MessageType       `json:"msg_type"`
	Source      string            `json:"source"`
	Destination string            `json:"dest"`
	ContentType string            `json:"content_type,omitempty"`
	Headers     []string          `json:"headers,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	Payload     []byte            `json:"payload,omitempty"`
	PartnerIDs  []string          `json:"partner_ids,omitempty"`
	SessionID   string            `json:"session_id,omitempty"`
}

SimpleEvent represents a WRP message of type SimpleEventMessageType.

This type implements Routable, and as such has a Response method. However, in actual practice failure responses are not sent for messages of this type. Response is merely supplied in order to satisfy the Routable interface.

https://github.com/xmidt-org/wrp-c/wiki/Web-Routing-Protocol#simple-event-definition

Deprecated: A future version of wrp will remove this type.

func (*SimpleEvent) BeforeEncode

func (msg *SimpleEvent) BeforeEncode() error

func (*SimpleEvent) CodecDecodeSelf

func (x *SimpleEvent) CodecDecodeSelf(d *codec1978.Decoder)

func (*SimpleEvent) CodecEncodeSelf

func (x *SimpleEvent) CodecEncodeSelf(e *codec1978.Encoder)

func (*SimpleEvent) From

func (msg *SimpleEvent) From() string

func (*SimpleEvent) IsCodecEmpty added in v3.1.0

func (x *SimpleEvent) IsCodecEmpty() bool

func (*SimpleEvent) IsTransactionPart

func (msg *SimpleEvent) IsTransactionPart() bool

IsTransactionPart for SimpleEvent types always returns false

func (*SimpleEvent) MessageType

func (msg *SimpleEvent) MessageType() MessageType

func (*SimpleEvent) Response

func (msg *SimpleEvent) Response(newSource string, requestDeliveryResponse int64) Routable

func (*SimpleEvent) To

func (msg *SimpleEvent) To() string

func (*SimpleEvent) TransactionKey

func (msg *SimpleEvent) TransactionKey() string

type SimpleRequestResponse deprecated

type SimpleRequestResponse struct {
	// Type is exposed principally for encoding.  This field *must* be set to SimpleRequestResponseMessageType,
	// and is automatically set by the BeforeEncode method.
	Type                    MessageType       `json:"msg_type"`
	Source                  string            `json:"source"`
	Destination             string            `json:"dest"`
	ContentType             string            `json:"content_type,omitempty"`
	Accept                  string            `json:"accept,omitempty"`
	TransactionUUID         string            `json:"transaction_uuid,omitempty"`
	Status                  *int64            `json:"status,omitempty"`
	RequestDeliveryResponse *int64            `json:"rdr,omitempty"`
	Headers                 []string          `json:"headers,omitempty"`
	Metadata                map[string]string `json:"metadata,omitempty"`
	Spans                   [][]string        `json:"spans,omitempty"`
	IncludeSpans            *bool             `json:"include_spans,omitempty"`
	Payload                 []byte            `json:"payload,omitempty"`
	PartnerIDs              []string          `json:"partner_ids,omitempty"`
}

SimpleRequestResponse represents a WRP message of type SimpleRequestResponseMessageType.

https://github.com/xmidt-org/wrp-c/wiki/Web-Routing-Protocol#simple-request-response-definition

Deprecated: A future version of wrp will remove this type.

func (*SimpleRequestResponse) BeforeEncode

func (msg *SimpleRequestResponse) BeforeEncode() error

func (*SimpleRequestResponse) CodecDecodeSelf

func (x *SimpleRequestResponse) CodecDecodeSelf(d *codec1978.Decoder)

func (*SimpleRequestResponse) CodecEncodeSelf

func (x *SimpleRequestResponse) CodecEncodeSelf(e *codec1978.Encoder)

func (*SimpleRequestResponse) FindEventStringSubMatch

func (msg *SimpleRequestResponse) FindEventStringSubMatch() string

func (*SimpleRequestResponse) From

func (msg *SimpleRequestResponse) From() string

func (*SimpleRequestResponse) IsCodecEmpty added in v3.1.0

func (x *SimpleRequestResponse) IsCodecEmpty() bool

func (*SimpleRequestResponse) IsTransactionPart

func (msg *SimpleRequestResponse) IsTransactionPart() bool

func (*SimpleRequestResponse) MessageType

func (msg *SimpleRequestResponse) MessageType() MessageType

func (*SimpleRequestResponse) Response

func (msg *SimpleRequestResponse) Response(newSource string, requestDeliveryResponse int64) Routable

func (*SimpleRequestResponse) SetIncludeSpans

func (msg *SimpleRequestResponse) SetIncludeSpans(value bool) *SimpleRequestResponse

SetIncludeSpans simplifies setting the optional IncludeSpans field, which is a pointer type tagged with omitempty.

func (*SimpleRequestResponse) SetRequestDeliveryResponse

func (msg *SimpleRequestResponse) SetRequestDeliveryResponse(value int64) *SimpleRequestResponse

SetRequestDeliveryResponse simplifies setting the optional RequestDeliveryResponse field, which is a pointer type tagged with omitempty.

func (*SimpleRequestResponse) SetStatus

func (msg *SimpleRequestResponse) SetStatus(value int64) *SimpleRequestResponse

SetStatus simplifies setting the optional Status field, which is a pointer type tagged with omitempty.

func (*SimpleRequestResponse) To

func (msg *SimpleRequestResponse) To() string

func (*SimpleRequestResponse) TransactionKey

func (msg *SimpleRequestResponse) TransactionKey() string

type Typed

type Typed interface {
	// MessageType is the type of message represented by this Typed.
	MessageType() MessageType
}

Typed is implemented by any WRP type which is associated with a MessageType. All message types implement this interface.

type Unknown deprecated

type Unknown struct {
	// Type is exposed principally for encoding.  This field *must* be set to UnknownMessageType,
	// and is automatically set by the BeforeEncode method.
	Type MessageType `json:"msg_type"`
}

Unknown represents a WRP message of type UnknownMessageType.

https://github.com/xmidt-org/wrp-c/wiki/Web-Routing-Protocol#unknown-message-definition

Deprecated: A future version of wrp will remove this type.

func (*Unknown) BeforeEncode

func (msg *Unknown) BeforeEncode() error

func (*Unknown) CodecDecodeSelf

func (x *Unknown) CodecDecodeSelf(d *codec1978.Decoder)

func (*Unknown) CodecEncodeSelf

func (x *Unknown) CodecEncodeSelf(e *codec1978.Encoder)

func (*Unknown) IsCodecEmpty added in v3.1.0

func (x *Unknown) IsCodecEmpty() bool

Directories

Path Synopsis
Package wrpendpoint integrates go-kit endpoints with the notion of services that consume and emit WRP.
Package wrpendpoint integrates go-kit endpoints with the notion of services that consume and emit WRP.
Package wrphttp integrates go-kit's transport/http package with the patterns used by WebPA/XMiDT servers.
Package wrphttp integrates go-kit's transport/http package with the patterns used by WebPA/XMiDT servers.
Package wrpmeta provides a simple API for building WRP message metadata
Package wrpmeta provides a simple API for building WRP message metadata

Jump to

Keyboard shortcuts

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