elemental

package module
v0.0.0-...-7b3109d Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2023 License: Apache-2.0 Imports: 24 Imported by: 1

README

elemental

Codacy Badge Codacy Badge

Note: This is a work in progress

Elemental contains the foundations and code generator to translate and use Regolithe specifications in a Bahamut/Manipulate environment. It also provides basic definition of a generic request and response and other low level functions like optimized encoder and decoder, validations and more.

The generated model from Regolithe specifications (when using elegen from cmd/elegen) will implement the interfaces described in this package to serve as a base for being used in a bahamut microservice.

Documentation

Overview

Package elemental provides a set of interfaces and structures used to manage a model generated from a Regolithe Specifications Set.

If you are not familiar with with Regolithe, please read https://github.com/aporeto-inc/regolithe.

Elemental is the basis of Bahamut (https://github.com/aporeto-inc/bahamut) and Manipulate (https://github.com/aporeto-inc/manipulate).

The main interface it provides is the Identifiable. This interface must be implemented by all object of a model. It allows to identify an object from its Identity (which is a name and category) and by its identifier. It also embeds the Versionable interface that allows to retrieve the current version of the model. The Identifiables interface must be implemented by lists managing a collection of Identifiable entities.

The ModelManager is an interface to perform lookup on Identities, Relationships between them and also allow to instantiate objects based on their Identity.

Elemental also contains some Request/Response structures representing various Operation on Identifiable or Identifiables as well as a bunch of validators to enforce specification constraints on attributes like max length, pattern etc. There is also an Event structure that can be used to notify clients of the the result of an Operation sent through a Request.

Elemental is mainly an abstract package and cannot really be used by itself. You must use the provided command (elegen) to generate an Elemental Model from a Regolithe Specification Set.

Index

Constants

This section is empty.

Variables

View Source
var AllIdentity = Identity{
	Name:     "*",
	Category: "*",
}

AllIdentity represents all possible Identities.

View Source
var BackwardCompatPropagation = false

BackwardCompatPropagation controls weither the 'propagated' flag should be removed or not. Set it to true to keep it and let the application access this flag from the query parameters in addition to Request.Propagated.

View Source
var EmptyIdentity = Identity{
	Name:     "",
	Category: "",
}

EmptyIdentity represents an empty Identity.

View Source
var RootIdentity = Identity{
	Name:     "root",
	Category: "root",
}

RootIdentity represents an root Identity.

Functions

func AtomicJob

func AtomicJob(job func() error) func(context.Context) error

AtomicJob takes a func() error and returns a func(context.Context) error. The returned function can be called as many time as you like, but only one instance of the given job can be run at the same time.

The returned function will either execute job if it it not already running or wait for the currently running job to finish. In both cases, the returned error from the job will be forwareded and returned to every caller.

You must pass a context.Context to the returned function so you can control how much time you are willing to wait for the job to complete.

If you wish to change some external state from within the job function, it is your responsibility to ensure everything is thread safe.

func BackportUnexposedFields

func BackportUnexposedFields(src, dest AttributeSpecifiable)

BackportUnexposedFields copy the values of unexposed fields from src to dest.

func Convert

func Convert(from EncodingType, to EncodingType, data []byte) ([]byte, error)

Convert converts from one EncodingType to another

func Decode

func Decode(encoding EncodingType, data []byte, dest interface{}) error

Decode decodes the given data using an appropriate decoder chosen from the given encoding.

func Encode

func Encode(encoding EncodingType, obj interface{}) ([]byte, error)

Encode encodes the given object using an appropriate encoder chosen from the given acceptType.

func EncodingFromHeaders

func EncodingFromHeaders(header http.Header) (read EncodingType, write EncodingType, err error)

EncodingFromHeaders returns the read (Content-Type) and write (Accept) encoding from the given http.Header.

func IsErrorWithCode

func IsErrorWithCode(err error, code int) bool

IsErrorWithCode returns true if the given error is an elemental.Error or elemental.Errors with the status set to the given code.

func IsNamespaceChildrenOfNamespace

func IsNamespaceChildrenOfNamespace(ns string, parent string) bool

IsNamespaceChildrenOfNamespace returns true of the given ns is a children of the given parent.

func IsNamespaceParentOfNamespace

func IsNamespaceParentOfNamespace(ns string, child string) bool

IsNamespaceParentOfNamespace returns true if the given namespace is a parent of the given parent

func IsNamespaceRelatedToNamespace

func IsNamespaceRelatedToNamespace(ns string, parent string) bool

IsNamespaceRelatedToNamespace returns true if the given namespace is related to the given parent

func IsOperationAllowed

func IsOperationAllowed(registry RelationshipsRegistry, i Identity, pid Identity, op Operation) bool

IsOperationAllowed returns true if given operatation on the given identity with the given parent is allowed.

func IsValidationError

func IsValidationError(err error, title string, attribute string) bool

IsValidationError returns true if the given error is a validation error with the given title for the given attribute.

func IsZero

func IsZero(o interface{}) bool

IsZero returns true if the given value is set to its Zero value.

func MakeStreamDecoder

func MakeStreamDecoder(encoding EncodingType, reader io.Reader) (func(dest interface{}) error, func())

MakeStreamDecoder returns a function that can be used to decode a stream from the given reader using the given encoding.

This function returns the decoder function that can be called until it returns an io.EOF error, indicating the stream is over, and a dispose function that will put back the decoder in the memory pool. The dispose function will be called automatically when the decoding is over, but not on a single decoding error. In any case, the dispose function should be always called, in a defer for example.

func MakeStreamEncoder

func MakeStreamEncoder(encoding EncodingType, writer io.Writer) (func(obj interface{}) error, func())

MakeStreamEncoder returns a function that can be user en encode given data into the given io.Writer using the given encoding.

It also returns a function must be called once the encoding procedure is complete, so the internal encoders can be put back into the shared memory pools.

func MatchesFilter

func MatchesFilter(identifiable AttributeSpecifiable, filter *Filter, opts ...MatcherOption) (bool, error)

MatchesFilter determines whether an identity matches a filter

func NamespaceAncestorsNames

func NamespaceAncestorsNames(namespace string) []string

NamespaceAncestorsNames returns the list of fully qualified namespaces in the hierarchy of a given namespace. It returns an empty array for the root namespace

func ParentNamespaceFromString

func ParentNamespaceFromString(namespace string) (string, error)

ParentNamespaceFromString returns the parent namespace of a namespace It returns empty it the string is invalid

func RegisterSupportedAcceptType

func RegisterSupportedAcceptType(mimetype string)

RegisterSupportedAcceptType registers a new media type that elemental should support for Accept. Note that this needs external intervention to handle decoding.

func RegisterSupportedContentType

func RegisterSupportedContentType(mimetype string)

RegisterSupportedContentType registers a new media type that elemental should support for Content-Type. Note that this needs external intervention to handle encoding.

func RemoveZeroValues

func RemoveZeroValues(obj interface{})

RemoveZeroValues reset all pointer fields that are pointing to a zero value to nil

func ResetDefaultForZeroValues

func ResetDefaultForZeroValues(obj interface{})

ResetDefaultForZeroValues reset the default value from the specification when a field is Zero. If the given object is not an elemental.AttributeSpecifiable this function does nothing.

func ResetMaps

func ResetMaps(v reflect.Value)

ResetMaps recursively empty all kinds of maps in the given reflect.Value.

func ResetSecretAttributesValues

func ResetSecretAttributesValues(obj interface{})

ResetSecretAttributesValues will reset any attributes marked as `secret` in the given obj if it is an elemental.Identifiable or an elemental.Identifiables. The given Identifiables must implement the elemental.AttributeSpecifiable interface or this function will have no effect.

If you pass anything else, this function does nothing.

func SetNamespacer

func SetNamespacer(custom Namespacer)

SetNamespacer will configure the package. It must be only called once and it is global for the package.

func ValidateAdvancedSpecification

func ValidateAdvancedSpecification(obj AttributeSpecifiable, pristine AttributeSpecifiable, op Operation) error

ValidateAdvancedSpecification verifies advanced specifications attributes like ReadOnly and CreationOnly.

For instance, it will check if the given Manipulable has field marked as readonly, that it has not changed according to the db.

func ValidateFloatInList

func ValidateFloatInList(attribute string, value float64, enums []float64) error

ValidateFloatInList validates if the string is in the list.

func ValidateFloatInMap

func ValidateFloatInMap(attribute string, value float64, enums map[float64]interface{}) error

ValidateFloatInMap validates if the string is in the list.

func ValidateIntInList

func ValidateIntInList(attribute string, value int, enums []int) error

ValidateIntInList validates if the string is in the list.

func ValidateIntInMap

func ValidateIntInMap(attribute string, value int, enums map[int]interface{}) error

ValidateIntInMap validates if the string is in the list.

func ValidateMaximumFloat

func ValidateMaximumFloat(attribute string, value float64, max float64, exclusive bool) error

ValidateMaximumFloat validates a float against a maximum value.

func ValidateMaximumInt

func ValidateMaximumInt(attribute string, value int, max int, exclusive bool) error

ValidateMaximumInt validates a integer against a maximum value.

func ValidateMaximumLength

func ValidateMaximumLength(attribute string, value string, max int, exclusive bool) error

ValidateMaximumLength validates the maximum length of a string.

func ValidateMinimumFloat

func ValidateMinimumFloat(attribute string, value float64, min float64, exclusive bool) error

ValidateMinimumFloat validates a float against a maximum value.

func ValidateMinimumInt

func ValidateMinimumInt(attribute string, value int, min int, exclusive bool) error

ValidateMinimumInt validates a integer against a maximum value.

func ValidateMinimumLength

func ValidateMinimumLength(attribute string, value string, min int, exclusive bool) error

ValidateMinimumLength validates the minimum length of a string.

func ValidatePattern

func ValidatePattern(attribute string, value string, pattern string, message string, required bool) error

ValidatePattern validates a string against a regular expression.

func ValidateRequiredExternal

func ValidateRequiredExternal(attribute string, value interface{}) error

ValidateRequiredExternal validates if the given value is null or not

func ValidateRequiredFloat

func ValidateRequiredFloat(attribute string, value float64) error

ValidateRequiredFloat validates is the int is set to 0.

func ValidateRequiredInt

func ValidateRequiredInt(attribute string, value int) error

ValidateRequiredInt validates is the int is set to 0.

func ValidateRequiredString

func ValidateRequiredString(attribute string, value string) error

ValidateRequiredString validates if the string is empty.

func ValidateRequiredTime

func ValidateRequiredTime(attribute string, value time.Time) error

ValidateRequiredTime validates if the time is empty.

func ValidateStringInList

func ValidateStringInList(attribute string, value string, enums []string, autogenerated bool) error

ValidateStringInList validates if the string is in the list.

func ValidateStringInMap

func ValidateStringInMap(attribute string, value string, enums map[string]interface{}, autogenerated bool) error

ValidateStringInMap validates if the string is in the list.

Types

type AttributeEncryptable

type AttributeEncryptable interface {
	EncryptAttributes(encrypter AttributeEncrypter) error
	DecryptAttributes(encrypter AttributeEncrypter) error
}

AttributeEncryptable is the interface of on object that has encryptable

type AttributeEncrypter

type AttributeEncrypter interface {

	// EncryptString encrypts the given string and returns the encrypted version.
	EncryptString(string) (string, error)

	// DecryptString decrypts the given string and returns the encrypted version.
	DecryptString(string) (string, error)
}

AttributeEncrypter is the interface that must be implement to manage encrypted attributes.

func NewAESAttributeEncrypter

func NewAESAttributeEncrypter(passphrase string) (AttributeEncrypter, error)

NewAESAttributeEncrypter returns a new elemental.AttributeEncrypter implementing AES encryption.

type AttributeSpecifiable

type AttributeSpecifiable interface {

	// SpecificationForAttribute returns the AttributeSpecification for
	// given attribute name
	SpecificationForAttribute(string) AttributeSpecification

	// AttributeSpecifications returns all the AttributeSpecification mapped by
	// attribute name
	AttributeSpecifications() map[string]AttributeSpecification

	// ValueForAttribute returns the value for the given attribute
	ValueForAttribute(name string) interface{}
}

An AttributeSpecifiable is the interface an object must implement in order to access specification of its attributes.

type AttributeSpecification

type AttributeSpecification struct {

	// AllowedChars is a regexp that will be used to validate
	// what value a string attribute can take.
	//
	// This is enforced by elemental.
	AllowedChars string

	// AllowedChoices is a list of possible values for an attribute.
	//
	// This is enforced by elemental.
	AllowedChoices []string

	// Autogenerated defines if the attribute is autogenerated by the server.
	// It can be used in conjunction with ReadOnly.
	//
	// This is not enforced by elemental. You must write your own business logic to honor this.
	Autogenerated bool

	// Availability is reserved for later use.
	Availability string

	// BSONFieldName is the name of the field that will be used when encoding/decoding the field into Binary JSON format.
	BSONFieldName string

	// ConvertedName contains the name after local conversion.
	ConvertedName string

	// Channel is reserved for later use.
	Channel string

	// CreationOnly defines if the attribute can be set only during creation.
	//
	// This is not enforced by elemental. You must write your own business logic to honor this.
	CreationOnly bool

	// DefaultValue holds the default value declared in specification.
	DefaultValue interface{}

	// Deprecated defines if the attribute is deprecated.
	Deprecated bool

	// Description contains the description of the attribute.
	Description string

	// Exposed defines if the attribute is exposed through the north bound API.
	Exposed bool

	// Filterable defines if it is possible to filter based on this attribute.
	//
	// This is not enforced by elemental. You must write your own business logic to honor this.
	Filterable bool

	// ForeignKey defines if the attribute is a foreign key.
	ForeignKey bool

	// Getter defines if the attribute needs to define a getter method.
	// This is useful if you can to define an Interface based on this attribute.
	Getter bool

	// Identifier defines if the attribute is used the access key from the
	// northbound API.
	Identifier bool

	// Index defines if the attribute is indexed or not.
	//
	// This is not enforced by elemental. You must write your own business logic to honor this.
	Index bool

	// MaxLength defines what is the maximun length of the attribute.
	// This only makes sense if the type is a string.
	//
	// This is enforced by elemental.
	MaxLength uint

	// MaxValue defines what is the maximun value of the attribute.
	// This only makes sense if the type has a numeric type.
	//
	// This is enforced by elemental.
	MaxValue float64

	// MinLength defines what is the minimum length of the attribute.
	// This only makes sense if the type is a string.
	//
	// This is enforced by elemental.
	MinLength uint

	// MinValue defines what is the minimum value of the attribute.
	// This only makes sense if the type has a numeric type.
	//
	// This is enforced by elemental.
	MinValue float64

	// Name defines what is the name of the attribute.
	// This will be the raw Monolithe Specification name, without
	// Go translation.
	Name string

	// Orderable defines if it is possible to order based on the value of this attribute.
	//
	// This is not enforced by elemental. You must write your own business logic to honor this.
	Orderable bool

	// PrimaryKey defines if the attribute is used as a primary key.
	PrimaryKey bool

	// ReadOnly defines if the attribute is read only.
	//
	// This is not enforced by elemental. You must write your own business logic to honor this.
	ReadOnly bool

	// Required defines is the attribute must be set or not.
	//
	// This is enforced by elemental.
	Required bool

	// Secret defines if the attribute is secret.
	// This is useful if you can to define perform sanity check on this field to be sure it
	// is not sent for instance.
	Secret bool

	// Setter defines if the attribute needs to define a setter method.
	// This is useful if you can to define an Interface based on this attribute.
	Setter bool

	// Signed indicates if the attribute's value should be used when
	// generating a signature for the object.
	Signed bool

	// Stored defines if the attribute will be stored in the northbound API.
	//
	// If this is true, the backend tags will be generated by Monolithe.
	Stored bool

	// SubType defines the Monolithe Subtype.
	SubType string

	// Transient defines if the attributes is transient or not.
	//
	// This is not enforced by elemental. You must write your own business logic to honor this.
	Transient bool

	// Type defines the raw Monolithe type.
	Type string

	// Encrypted defines if the attribute needs encryption.
	Encrypted bool
}

An AttributeSpecification represents all the metadata of an attribute.

This information is coming from the Monolithe Specifications.

type Decoder

type Decoder interface {
	Decode(dst interface{}) error
	Encodable
}

A Decoder is an Encodable that can be decoded.

type DefaultOrderer

type DefaultOrderer interface {

	// Default order returns the keys that can be used for default ordering.
	DefaultOrder() []string
}

DefaultOrderer is the interface of an object that has default ordering fields.

type Documentable

type Documentable interface {
	Doc() string
}

A Documentable is an object that can be documented.

type Encodable

type Encodable interface {
	GetEncoding() EncodingType
}

An Encodable is the interface of objects that can hold encoding information.

type Encoder

type Encoder interface {
	Encode(obj interface{}) (err error)
	Encodable
}

A Encoder is an Encodable that can be encoded.

type EncodingType

type EncodingType string

An EncodingType represents one type of data encoding

const (
	EncodingTypeJSON    EncodingType = "application/json"
	EncodingTypeMSGPACK EncodingType = "application/msgpack"
)

Various values for EncodingType.

type ErrUnsupportedComparator

type ErrUnsupportedComparator struct {
	Err error
}

ErrUnsupportedComparator is the error type that will be returned in the event that that an unsupported comparator is used in the filter.

func (ErrUnsupportedComparator) Error

func (e ErrUnsupportedComparator) Error() string

func (ErrUnsupportedComparator) Is

Is reports whether the provided error has the same type as ErrUnsupportedComparator. This was added as part of the new error handling APIs added to Go 1.13

func (ErrUnsupportedComparator) Unwrap

func (e ErrUnsupportedComparator) Unwrap() error

Unwrap returns the embedded error in ErrUnsupportedComparator.

type Error

type Error struct {
	Code        int         `msgpack:"code" json:"code,omitempty"`
	Description string      `msgpack:"description" json:"description"`
	Subject     string      `msgpack:"subject" json:"subject"`
	Title       string      `msgpack:"title" json:"title"`
	Data        interface{} `msgpack:"data" json:"data,omitempty"`
	Trace       string      `msgpack:"trace" json:"trace,omitempty"`
}

An Error represents a computational error.

They can be encoded and sent back to the clients.

func NewError

func NewError(title, description, subject string, code int) Error

NewError returns a new Error.

func NewErrorWithData

func NewErrorWithData(title, description, subject string, code int, data interface{}) Error

NewErrorWithData returns a new Error with the given opaque data.

func (Error) Error

func (e Error) Error() string

type Errors

type Errors []Error

Errors represents a list of Error.

func DecodeErrors

func DecodeErrors(data []byte) (Errors, error)

DecodeErrors decodes the given bytes into a en elemental.Errors.

func NewErrors

func NewErrors(errors ...error) Errors

NewErrors creates a new Errors.

func (Errors) Append

func (e Errors) Append(errs ...error) Errors

Append returns returns a copy of the receiver containing also the given errors.

func (Errors) Code

func (e Errors) Code() int

Code returns the code of the first error code in the Errors.

func (Errors) Error

func (e Errors) Error() string

func (Errors) Trace

func (e Errors) Trace(id string) Errors

Trace returns Errors with all inside Error marked with the given trace ID.

type Event

type Event struct {
	RawData   []byte          `msgpack:"entity" json:"-"`
	JSONData  json.RawMessage `msgpack:"-" json:"entity"`
	Identity  string          `msgpack:"identity" json:"identity"`
	Type      EventType       `msgpack:"type" json:"type"`
	Timestamp time.Time       `msgpack:"timestamp" json:"timestamp"`
	Encoding  EncodingType    `msgpack:"encoding" json:"encoding"`
}

An Event represents a computational event.

func NewErrorEvent

func NewErrorEvent(ee Error, encoding EncodingType) *Event

NewErrorEvent returns a new (error) Event embedded with the provided elemental.Error

func NewEvent

func NewEvent(t EventType, o Identifiable) *Event

NewEvent returns a new Event.

func NewEventWithEncoding

func NewEventWithEncoding(t EventType, o Identifiable, encoding EncodingType) *Event

NewEventWithEncoding returns a new Event using the given encoding

func (*Event) Convert

func (e *Event) Convert(encoding EncodingType) error

Convert converts the internal encoded data to the given encoding.

func (*Event) Decode

func (e *Event) Decode(dst interface{}) error

Decode decodes the data into the given destination.

func (*Event) Duplicate

func (e *Event) Duplicate() *Event

Duplicate creates a copy of the event.

func (*Event) Entity

func (e *Event) Entity() []byte

Entity returns the byte encoded entity.

func (*Event) GetEncoding

func (e *Event) GetEncoding() EncodingType

GetEncoding returns the encoding used to encode the entity.

func (*Event) String

func (e *Event) String() string

type EventType

type EventType string

EventType is the type of an event.

const (
	// EventCreate is the type of creation events.
	EventCreate EventType = "create"

	// EventUpdate is the type of update events.
	EventUpdate EventType = "update"

	// EventDelete is the type of delete events.
	EventDelete EventType = "delete"

	// EventError is the type of error events.
	EventError EventType = "error"
)

type Events

type Events []*Event

An Events represents a list of Event.

func NewEvents

func NewEvents(events ...*Event) Events

NewEvents retutns a new Events.

type Filter

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

Filter is a filter struct which can be used with Cassandra

func NewFilter

func NewFilter() *Filter

NewFilter returns a new filter.

func NewFilterFromString

func NewFilterFromString(filter string) (*Filter, error)

NewFilterFromString returns a new filter computed from the given string.

func (*Filter) And

func (f *Filter) And(filters ...*Filter) FilterKeyComposer

And adds a new sub filter to FilterComposer.

func (*Filter) AndFilters

func (f *Filter) AndFilters() SubFilters

AndFilters returns the current and sub filters.

func (*Filter) Comparators

func (f *Filter) Comparators() FilterComparators

Comparators returns the current comparators.

func (*Filter) Contains

func (f *Filter) Contains(values ...interface{}) FilterKeyComposer

Contains adds a contains comparator to the FilterComposer.

func (*Filter) Done

func (f *Filter) Done() *Filter

Done terminates the filter composition and returns the *Filter.

func (*Filter) Equals

func (f *Filter) Equals(value interface{}) FilterKeyComposer

Equals adds a an equality comparator to the FilterComposer.

func (*Filter) Exists

func (f *Filter) Exists() FilterKeyComposer

Exists adds an exists comparator to the FilterComposer.

func (*Filter) GreaterOrEqualThan

func (f *Filter) GreaterOrEqualThan(value interface{}) FilterKeyComposer

GreaterOrEqualThan adds a greater than (inclusive) comparator to the FilterComposer.

func (*Filter) GreaterThan

func (f *Filter) GreaterThan(value interface{}) FilterKeyComposer

GreaterThan adds a greater than (exclusive) comparator to the FilterComposer.

func (*Filter) In

func (f *Filter) In(values ...interface{}) FilterKeyComposer

In adds a in comparator to the FilterComposer.

func (*Filter) Keys

func (f *Filter) Keys() FilterKeys

Keys returns the current keys.

func (*Filter) LesserOrEqualThan

func (f *Filter) LesserOrEqualThan(value interface{}) FilterKeyComposer

LesserOrEqualThan adds a lesser than (inclusive) comparator to the FilterComposer.

func (*Filter) LesserThan

func (f *Filter) LesserThan(value interface{}) FilterKeyComposer

LesserThan adds a lesser than (exclusive) comparator to the FilterComposer.

func (*Filter) Matches

func (f *Filter) Matches(values ...interface{}) FilterKeyComposer

Matches adds a match comparator to the FilterComposer.

func (*Filter) NotContains

func (f *Filter) NotContains(values ...interface{}) FilterKeyComposer

NotContains adds a contains comparator to the FilterComposer.

func (*Filter) NotEquals

func (f *Filter) NotEquals(value interface{}) FilterKeyComposer

NotEquals adds a an non equality comparator to the FilterComposer.

func (*Filter) NotExists

func (f *Filter) NotExists() FilterKeyComposer

NotExists adds an not exist comparator to the FilterComposer.

func (*Filter) NotIn

func (f *Filter) NotIn(values ...interface{}) FilterKeyComposer

NotIn adds a not in comparator to the FilterComposer.

func (*Filter) Operators

func (f *Filter) Operators() FilterOperators

Operators returns the current operators.

func (*Filter) Or

func (f *Filter) Or(filters ...*Filter) FilterKeyComposer

Or adds a new sub filter to FilterComposer.

func (*Filter) OrFilters

func (f *Filter) OrFilters() SubFilters

OrFilters returns the current ors sub filters.

func (*Filter) String

func (f *Filter) String() string

func (*Filter) Values

func (f *Filter) Values() FilterValues

Values returns the current values.

func (*Filter) WithKey

func (f *Filter) WithKey(key string) FilterValueComposer

WithKey adds a key to FilterComposer.

type FilterComparator

type FilterComparator int

An FilterComparator is the type of a operator used by a filter.

const (
	EqualComparator FilterComparator = iota
	NotEqualComparator
	GreaterComparator
	GreaterOrEqualComparator
	LesserComparator
	LesserOrEqualComparator
	InComparator
	NotInComparator
	ContainComparator
	NotContainComparator
	MatchComparator
	NotMatchComparator
	ExistsComparator
	NotExistsComparator
)

Comparators represent various comparison operations.

type FilterComparators

type FilterComparators []FilterComparator

FilterComparators are a list of FilterOperator.

type FilterKeyComposer

type FilterKeyComposer interface {
	WithKey(string) FilterValueComposer

	And(...*Filter) FilterKeyComposer
	Or(...*Filter) FilterKeyComposer

	Done() *Filter
}

FilterKeyComposer composes a filter.

func NewFilterComposer

func NewFilterComposer() FilterKeyComposer

NewFilterComposer returns a FilterComposer.

type FilterKeys

type FilterKeys []string

FilterKeys represents a list of FilterKey.

type FilterOperator

type FilterOperator int

An FilterOperator is the type of a operator used by a filter.

const (
	AndOperator FilterOperator = iota
	OrFilterOperator
	AndFilterOperator
)

Operators represent various operators.

type FilterOperators

type FilterOperators []FilterOperator

FilterOperators are a list of FilterOperator.

type FilterParser

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

FilterParser represents a Parser

func NewFilterParser

func NewFilterParser(input string, opts ...FilterParserOption) *FilterParser

NewFilterParser returns an instance of FilterParser for the given input

func (*FilterParser) Parse

func (p *FilterParser) Parse() (*Filter, error)

Parse parses the input string and returns a new Filter.

type FilterParserOption

type FilterParserOption func(*filterParserConfig)

FilterParserOption represents the type for the options that can be passed to `NewFilterParser` which can be used to alter parsing behaviour

func OptUnsupportedComparators

func OptUnsupportedComparators(blacklist []FilterComparator) FilterParserOption

OptUnsupportedComparators accepts a slice of comparators that will limit the set of comparators that the parser will accept. If supplied, the parser will return an error if the filter being parsed contains a comparator provided in the blacklist.

type FilterValue

type FilterValue []interface{}

FilterValue represents a filter value.

type FilterValueComposer

type FilterValueComposer interface {
	Equals(interface{}) FilterKeyComposer
	NotEquals(interface{}) FilterKeyComposer
	GreaterOrEqualThan(interface{}) FilterKeyComposer
	GreaterThan(interface{}) FilterKeyComposer
	LesserOrEqualThan(interface{}) FilterKeyComposer
	LesserThan(interface{}) FilterKeyComposer
	In(...interface{}) FilterKeyComposer
	NotIn(...interface{}) FilterKeyComposer
	Contains(...interface{}) FilterKeyComposer
	NotContains(...interface{}) FilterKeyComposer
	Matches(...interface{}) FilterKeyComposer
	Exists() FilterKeyComposer
	NotExists() FilterKeyComposer
}

FilterValueComposer adds values and operators.

type FilterValues

type FilterValues [][]interface{}

FilterValues represents a list of FilterValue.

type Identifiable

type Identifiable interface {

	// Identity returns the Identity of the of the receiver.
	Identity() Identity

	// Identifier returns the unique identifier of the of the receiver.
	Identifier() string

	// SetIdentifier sets the unique identifier of the of the receiver.
	SetIdentifier(string)

	Versionable
}

An Identifiable is the interface that Elemental objects must implement.

type Identifiables

type Identifiables interface {
	Identity() Identity
	List() IdentifiablesList
	Copy() Identifiables
	Append(...Identifiable) Identifiables
	Versionable
}

Identifiables is the interface of a list of Identifiable that can returns the Identity of the objects it contains.

type IdentifiablesList

type IdentifiablesList []Identifiable

An IdentifiablesList is a list of objects implementing the Identifiable interface.

type Identity

type Identity struct {
	Name     string `msgpack:"name" json:"name"`
	Category string `msgpack:"category" json:"category"`
	Private  bool   `msgpack:"-" json:"-"`
	Package  string `msgpack:"-" json:"-"`
}

An Identity is a structure that contains the necessary information about an Identifiable. The Name is usually the singular form of the Category.

For instance, "cat" and "cats".

func MakeIdentity

func MakeIdentity(name, category string) Identity

MakeIdentity returns a new Identity.

func (Identity) IsEmpty

func (i Identity) IsEmpty() bool

IsEmpty checks if the identity is empty.

func (Identity) IsEqual

func (i Identity) IsEqual(identity Identity) bool

IsEqual checks if the given identity is equal to the receiver.

func (Identity) String

func (i Identity) String() string

String returns the string representation of the identity.

type MatcherError

type MatcherError struct {
	Err error
}

MatcherError is the error type that will be returned by elemental.MatchesFilter in the event that it returns an error

func (*MatcherError) Error

func (me *MatcherError) Error() string

func (*MatcherError) Unwrap

func (me *MatcherError) Unwrap() error

Unwrap returns the the error contained in 'MatcherError'. This is a special method that aids in error handling for clients using Go 1.13 and beyond as they can now utilize the new 'Is' function added to the 'errors' package.

type MatcherOption

type MatcherOption func(*matchConfig)

MatcherOption represents the type for the options that can be passed to the helper `MatchesFilter` which can be used to alter the matching behaviour

type ModelManager

type ModelManager interface {

	// Identifiable returns an Identifiable with the given identity.
	Identifiable(Identity) Identifiable

	// SparseIdentifiable returns a SparseIdentifiable with the given identity.
	SparseIdentifiable(Identity) SparseIdentifiable

	// IdentifiableFromString returns an Identifiable from the given
	// string. The string can be an Identity name, category or alias.
	IdentifiableFromString(string) Identifiable

	// Identifiables returns an Identifiables with the given identity.
	Identifiables(Identity) Identifiables

	// SparseIdentifiables returns an Identifiables with the given identity.
	SparseIdentifiables(Identity) SparseIdentifiables

	// IdentifiablesFrom returns an Identifiables from the given
	// string. The string can be an Identity name, category or alias.
	IdentifiablesFromString(string) Identifiables

	// IdentityFromName returns the Identity from the given name.
	IdentityFromName(string) Identity

	// IdentityFromCategory returns the Identity from the given category.
	IdentityFromCategory(string) Identity

	// IdentityFromAlias returns the Identity from the given alias.
	IdentityFromAlias(string) Identity

	// IdentityFromAny returns the Identity from the given name, category or alias.
	IdentityFromAny(string) Identity

	// IndexesForIdentity returns the indexes of the given Identity.
	Indexes(Identity) [][]string

	// Relationships return the model's elemental.RelationshipsRegistry.
	Relationships() RelationshipsRegistry

	// AllIdentities return the list of all existing identities.
	AllIdentities() []Identity
}

An ModelManager is the interface that allows to search Identities and create Identifiable and Identifiables from Identities.

type Namespaceable

type Namespaceable interface {
	GetNamespace() string
	SetNamespace(string)
}

A Namespaceable is the interface of an object that is namespaced.

type Namespacer

type Namespacer interface {
	Extract(r *http.Request) (string, error)
	Inject(r *http.Request, namespace string) error
}

Namespacer is the interface that any namespace extraction/injection implementation should support.

func GetNamespacer

func GetNamespacer() Namespacer

GetNamespacer retrieves the configured namespacer.

type Operation

type Operation string

Operation represents an operation to apply on an Identifiable from a Request.

const (
	OperationRetrieveMany Operation = "retrieve-many"
	OperationRetrieve     Operation = "retrieve"
	OperationCreate       Operation = "create"
	OperationUpdate       Operation = "update"
	OperationDelete       Operation = "delete"
	OperationPatch        Operation = "patch"
	OperationInfo         Operation = "info"

	OperationEmpty Operation = ""
)

Here are the existing Operations.

func ParseOperation

func ParseOperation(op string) (Operation, error)

ParseOperation parses the given string as an Operation.

type Parameter

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

A Parameter represent one parameter that can be sent with a query.

func NewParameter

func NewParameter(ptype ParameterType, values ...interface{}) Parameter

NewParameter returns a new Parameter.

func (Parameter) BoolValue

func (p Parameter) BoolValue() bool

BoolValue returns the value as a bool.

func (Parameter) BoolValues

func (p Parameter) BoolValues() []bool

BoolValues returns all the values as a []bool.

func (Parameter) DurationValue

func (p Parameter) DurationValue() time.Duration

DurationValue returns the value as a time.Duration.

func (Parameter) DurationValues

func (p Parameter) DurationValues() []time.Duration

DurationValues returns all the values as a []time.Duration.

func (Parameter) FloatValue

func (p Parameter) FloatValue() float64

FloatValue returns the value as a float.

func (Parameter) FloatValues

func (p Parameter) FloatValues() []float64

FloatValues returns all the values as a []float64.

func (Parameter) IntValue

func (p Parameter) IntValue() int

IntValue returns the value as a int.

func (Parameter) IntValues

func (p Parameter) IntValues() []int

IntValues returns all the values as a []int.

func (Parameter) StringValue

func (p Parameter) StringValue() string

StringValue returns the value as a string.

func (Parameter) StringValues

func (p Parameter) StringValues() []string

StringValues returns all the values as a []string.

func (Parameter) TimeValue

func (p Parameter) TimeValue() time.Time

TimeValue returns the value as a time.Time.

func (Parameter) TimeValues

func (p Parameter) TimeValues() []time.Time

TimeValues returns all the values as a []time.Time.

func (Parameter) Values

func (p Parameter) Values() []interface{}

Values returns all the parsed values

type ParameterDefinition

type ParameterDefinition struct {
	Name           string
	Type           ParameterType
	AllowedChoices []string
	DefaultValue   string
	Multiple       bool
}

A ParameterDefinition represent a parameter definition that can be transformed into a Parameter.

func ParametersForOperation

func ParametersForOperation(registry RelationshipsRegistry, i Identity, pid Identity, op Operation) []ParameterDefinition

ParametersForOperation returns the parameters defined for the retrieve operation on the given identity.

func (*ParameterDefinition) Parse

func (p *ParameterDefinition) Parse(values []string) (*Parameter, error)

Parse parses the given value against the parameter definition

type ParameterType

type ParameterType string

ParameterType represents the various type for a parameter.

const (
	ParameterTypeString   ParameterType = "string"
	ParameterTypeInt      ParameterType = "integer"
	ParameterTypeFloat    ParameterType = "float"
	ParameterTypeBool     ParameterType = "boolean"
	ParameterTypeEnum     ParameterType = "enum"
	ParameterTypeTime     ParameterType = "time"
	ParameterTypeDuration ParameterType = "duration"
)

Various values for ParameterType.

type Parameters

type Parameters map[string]Parameter

Parameters represents a set of Parameters.

func (Parameters) Get

func (p Parameters) Get(name string) Parameter

Get returns the Parameter with the given name

func (Parameters) Validate

func (p Parameters) Validate(r ParametersRequirement) error

Validate validates if the Parameters matches the given requirement.

type ParametersRequirement

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

A ParametersRequirement represents a list of ors of ands that must be passed together.

For example:
	{{{"a"}, {"b", "c"}}} requires a or (b and c)
	{{{"a"}, {"b", "c"}, {{"d"}}} requires (a or (b and c)) and (d))

func NewParametersRequirement

func NewParametersRequirement(match [][][]string) ParametersRequirement

NewParametersRequirement returns a new ParametersRequirement.

func (ParametersRequirement) String

func (r ParametersRequirement) String() string

type Patchable

type Patchable interface {

	// Patch patches the receiver using the given SparseIdentifiable.
	Patch(SparseIdentifiable)
}

A Patchable the interface of an object that can be patched.

type PlainIdentifiable

type PlainIdentifiable interface {

	// ToSparse returns a sparsed version of the object.
	ToSparse(...string) SparseIdentifiable

	Identifiable
}

A PlainIdentifiable is the interface of an object that can return a sparse version of itself.

type PlainIdentifiables

type PlainIdentifiables interface {

	// ToSparse returns a sparsed version of the object.
	ToSparse(...string) Identifiables

	Identifiables
}

A PlainIdentifiables is the interface of an object that can return a sparse version of itself.

type Propagatable

type Propagatable interface {
	GetProgagate() bool
	Namespaceable
}

A Propagatable is the interface of an object that can propagate down from a parent namespace.

type PushConfig

type PushConfig struct {
	Identities      map[string][]EventType `msgpack:"identities" json:"identities"`
	IdentityFilters map[string]string      `msgpack:"filters"    json:"filters"`
	Params          url.Values             `msgpack:"parameters" json:"parameters"`
	// contains filtered or unexported fields
}

A PushConfig represents an abstract filter for filtering out push notifications.

The 'IdentityFilters' field is a mapping between a filtered identity and the string representation of an elemental.Filter. A client will supply this attribute if they want fine-grained filtering on the set of identities that they are filtering on. If this attribute has been supplied, the identities passed to 'IdentityFilters' must be a subset of the identities passed to 'Identities'; passing in identities that are not provided in the 'Identities' field will be ignored.

func NewPushConfig

func NewPushConfig() *PushConfig

NewPushConfig returns a new PushConfig.

func (*PushConfig) Duplicate

func (pc *PushConfig) Duplicate() *PushConfig

Duplicate duplicates the PushConfig.

func (*PushConfig) FilterForIdentity

func (pc *PushConfig) FilterForIdentity(identityName string) (*Filter, bool)

FilterForIdentity returns the associated fine-grained filter for the given identity. In the event that no fine-grained filter has been configured for the identity, the second return value (a boolean), will be set to false.

func (*PushConfig) FilterIdentity

func (pc *PushConfig) FilterIdentity(identityName string, eventTypes ...EventType)

FilterIdentity adds the given identity for the given eventTypes in the PushConfig.

func (*PushConfig) IsFilteredOut

func (pc *PushConfig) IsFilteredOut(identityName string, eventType EventType) bool

IsFilteredOut returns true if the given Identity is not part of the PushConfig's Identity mapping

func (*PushConfig) Parameters

func (pc *PushConfig) Parameters() url.Values

Parameters returns a copy of all the parameters.

func (*PushConfig) ParseIdentityFilters

func (pc *PushConfig) ParseIdentityFilters() error

ParseIdentityFilters parses the configured PushConfig's 'IdentityFilters' attribute to elemental filters. The parsed filters will then be stored in the non-exposed 'parsedIdentityFilters' attribute of PushConfig. This is useful for clients that wish the utilize the same filter multiple times without having to incur the overhead of parsing each time.

An error is returned in following situations:

  • when a filter is declared on an identity that is not defined in the PushConfig's 'Identities' attribute
  • when a filter cannot be parsed into an elemental.Filter

func (*PushConfig) SetParameter

func (pc *PushConfig) SetParameter(key string, values ...string)

SetParameter sets the values of the parameter with the given key.

func (*PushConfig) String

func (pc *PushConfig) String() string

type PushFilter deprecated

type PushFilter = PushConfig

A PushFilter represents an abstract filter for filtering out push notifications. This is now aliased to PushConfig as a result of re-naming the type.

Deprecated: use the new name PushConfig instead

func NewPushFilter deprecated

func NewPushFilter() *PushFilter

NewPushFilter returns a new PushFilter. NewPushFilter is now aliased to NewPushConfig. This was done for backwards compatibility as a result of the re-naming of PushFilter to PushConfig.

Deprecated: use the constructor with the new name, NewPushConfig, instead

type Relationship

type Relationship struct {
	Type string

	Retrieve     map[string]*RelationshipInfo
	RetrieveMany map[string]*RelationshipInfo
	Info         map[string]*RelationshipInfo
	Create       map[string]*RelationshipInfo
	Update       map[string]*RelationshipInfo
	Delete       map[string]*RelationshipInfo
	Patch        map[string]*RelationshipInfo
}

A Relationship describes the hierarchical relationship of the models.

type RelationshipInfo

type RelationshipInfo struct {
	Deprecated         bool
	Parameters         []ParameterDefinition
	RequiredParameters ParametersRequirement
}

A RelationshipInfo describe the various meta information of a relationship.

func RelationshipInfoForOperation

func RelationshipInfoForOperation(registry RelationshipsRegistry, i Identity, pid Identity, op Operation) *RelationshipInfo

RelationshipInfoForOperation returns the relationship info for the given identity, parent identity and operation.

type RelationshipsRegistry

type RelationshipsRegistry map[Identity]*Relationship

A RelationshipsRegistry maintains the relationship for Identities.

type Request

type Request struct {
	RequestID            string
	Namespace            string
	Recursive            bool
	Propagated           bool
	Operation            Operation
	Identity             Identity
	Order                []string
	ObjectID             string
	ParentIdentity       Identity
	ParentID             string
	Data                 []byte
	Parameters           Parameters
	Headers              http.Header
	Username             string
	Password             string
	Page                 int
	PageSize             int
	After                string
	Limit                int
	OverrideProtection   bool
	Version              int
	ExternalTrackingID   string
	ExternalTrackingType string
	ContentType          EncodingType
	Accept               EncodingType

	Metadata           map[string]interface{}
	ClientIP           string
	TLSConnectionState *tls.ConnectionState
	// contains filtered or unexported fields
}

A Request represents an abstract request on an elemental model.

func NewRequest

func NewRequest() *Request

NewRequest returns a new Request.

func NewRequestFromHTTPRequest

func NewRequestFromHTTPRequest(req *http.Request, manager ModelManager) (*Request, error)

NewRequestFromHTTPRequest returns a new Request from the given http.Request.

func (*Request) Decode

func (r *Request) Decode(dst interface{}) error

Decode decodes the data into the given destination.

func (*Request) Duplicate

func (r *Request) Duplicate() *Request

Duplicate duplicates the Request.

func (*Request) GetEncoding

func (r *Request) GetEncoding() EncodingType

GetEncoding returns the encoding used to encode the body.

func (*Request) HTTPRequest

func (r *Request) HTTPRequest() *http.Request

HTTPRequest returns the native http.Request, if any.

func (*Request) String

func (r *Request) String() string

type Response

type Response struct {
	StatusCode int
	Data       []byte
	Count      int
	Total      int
	Next       string
	Messages   []string
	Redirect   string
	RequestID  string
	Request    *Request
	Cookies    []*http.Cookie
}

A Response contains the response from a Request.

func NewResponse

func NewResponse(req *Request) *Response

NewResponse returns a new Response

func (*Response) Encode

func (r *Response) Encode(obj interface{}) (err error)

Encode encodes the given oject into the response.

func (*Response) GetEncoding

func (r *Response) GetEncoding() EncodingType

GetEncoding returns the encoding used to encode the entity.

type SparseIdentifiable

type SparseIdentifiable interface {

	// ToPlain returns the full version of the object.
	ToPlain() PlainIdentifiable

	Identifiable
}

A SparseIdentifiable is the interface of an object that can return a full version of itself.

type SparseIdentifiables

type SparseIdentifiables interface {

	// ToPlain returns the full version of the object.
	ToPlain() IdentifiablesList

	Identifiables
}

A SparseIdentifiables is the interface of an object that can return a full version of itself.

type SubFilter

type SubFilter []*Filter

SubFilter is the type of subfilter

type SubFilters

type SubFilters []SubFilter

SubFilters is is a list SubFilter,

type Validatable

type Validatable interface {
	Validate() error
}

A Validatable is the interface for objects that can be validated.

type Versionable

type Versionable interface {
	Version() int
}

A Versionable is an object that can be versioned.

Directories

Path Synopsis
cmd
Package internal is a generated GoMock package.
Package internal is a generated GoMock package.
test

Jump to

Keyboard shortcuts

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