api

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2023 License: Apache-2.0 Imports: 9 Imported by: 148

README

api

This repository defines some MOSN interfaces which can be implemented by others.

install

go get mosn.io/api

Documentation

Index

Constants

View Source
const (
	CodecExceptionCode    = 0
	UnknownCode           = 2
	DeserialExceptionCode = 3
	SuccessCode           = 200
	PermissionDeniedCode  = 403
	RouterUnavailableCode = 404
	InternalErrorCode     = 500
	NoHealthUpstreamCode  = 502
	UpstreamOverFlowCode  = 503
	TimeoutExceptionCode  = 504
	LimitExceededCode     = 509
)

status codes.

Variables

View Source
var (
	AlreadyRegistered = "protocol code already registered"
	UnknownType       = "unknown model type"
	UnrecognizedCode  = "unrecognized protocol code"
	NoProtocolCode    = "no protocol code found"

	ErrDupRegistered    = errors.New(AlreadyRegistered)
	ErrUnknownType      = errors.New(UnknownType)
	ErrUnrecognizedCode = errors.New(UnrecognizedCode)
	ErrNoProtocolCode   = errors.New(NoProtocolCode)
)

Error def

Functions

func HandleXDSConfig added in v1.1.0

func HandleXDSConfig(filterType string, s *any.Any) (map[string]interface{}, error)

HandleXDSConfig converts pb Any to map according to the filterType

func RegisterListener

func RegisterListener(filterType string, creator ListenerFilterFactoryCreator)

RegisterListener registers the filterType as ListenerFilterFactoryCreator

func RegisterNetwork

func RegisterNetwork(filterType string, creator NetworkFilterFactoryCreator)

RegisterNetwork registers the filterType as NetworkFilterFactoryCreator

func RegisterStream

func RegisterStream(filterType string, creator StreamFilterFactoryCreator)

RegisterStream registers the filterType as StreamFilterFactoryCreator

func RegisterXDSConfigHandler added in v1.1.0

func RegisterXDSConfigHandler(filterType string, creator XDSConfigHandler)

RegisterXDSConfigHandler registers the filterType as XDSConfigHandler

Types

type AccessLog

type AccessLog interface {
	// Log write the access info.
	Log(ctx context.Context, reqHeaders HeaderMap, respHeaders HeaderMap, requestInfo RequestInfo)
}

AccessLog is a log object that used to log the access info.

type ConnState

type ConnState int

Connection status

const (
	ConnInit ConnState = iota
	ConnActive
	ConnClosed
)

Connection statuses

type Connection

type Connection interface {
	// ID returns unique connection id
	ID() uint64

	// Start starts connection with context.
	// See context.go to get available keys in context
	Start(lctx context.Context)

	// Write writes data to the connection.
	// Called by other-side stream connection's read loop. Will loop through stream filters with the buffer if any are installed.
	Write(buf ...IoBuffer) error

	// Close closes connection with connection type and event type.
	// ConnectionCloseType - how to close to connection
	//      - FlushWrite: connection will be closed after buffer flushed to underlying io
	//      - NoFlush: close connection asap
	// ConnectionEvent - why to close the connection
	//      - RemoteClose
	//  - LocalClose
	//      - OnReadErrClose
	//  - OnWriteErrClose
	//  - OnConnect
	//  - Connected:
	//      - ConnectTimeout
	//      - ConnectFailed
	Close(ccType ConnectionCloseType, eventType ConnectionEvent) error

	// LocalAddr returns the local address of the connection.
	// For client connection, this is the origin address
	// For server connection, this is the proxy's address
	// TODO: support get local address in redirected request
	// TODO: support transparent mode
	LocalAddr() net.Addr

	// RemoteAddr returns the remote address of the connection.
	RemoteAddr() net.Addr

	// SetRemoteAddr is used for originaldst we need to replace remoteAddr
	SetRemoteAddr(address net.Addr)

	// AddConnectionEventListener add a listener method will be called when connection event occur.
	AddConnectionEventListener(listener ConnectionEventListener)

	// OnConnectionEvent callback all ConnectionEventListener for this connection
	OnConnectionEvent(event ConnectionEvent)

	// AddBytesReadListener add a method will be called everytime bytes read
	AddBytesReadListener(listener func(bytesRead uint64))

	// AddBytesSentListener add a method will be called everytime bytes write
	AddBytesSentListener(listener func(bytesSent uint64))

	// NextProtocol returns network level negotiation, such as ALPN. Returns empty string if not supported.
	NextProtocol() string

	// SetNoDelay enable/disable tcp no delay
	SetNoDelay(enable bool)

	// SetReadDisable enable/disable read on the connection.
	// If reads are enabled after disable, connection continues to read and data will be dispatched to read filter chains.
	SetReadDisable(disable bool)

	// ReadEnabled returns whether reading is enabled on the connection.
	ReadEnabled() bool

	// TLS returns a related tls connection.
	TLS() net.Conn

	// SetBufferLimit set the buffer limit.
	SetBufferLimit(limit uint32)

	// BufferLimit returns the buffer limit.
	BufferLimit() uint32

	// SetLocalAddress sets a local address
	SetLocalAddress(localAddress net.Addr, restored bool)

	// SetCollector set read/write mertics collectors
	SetCollector(read, write metrics.Counter)
	// LocalAddressRestored returns whether local address is restored
	// TODO: unsupported now
	LocalAddressRestored() bool

	// GetWriteBuffer is used by network writer filter
	GetWriteBuffer() []IoBuffer

	// GetReadBuffer is used by network read filter
	GetReadBuffer() IoBuffer

	// FilterManager returns the FilterManager
	FilterManager() FilterManager

	// RawConn returns the original connections.
	// Caution: raw conn only used in io-loop disable mode
	// TODO: a better way to provide raw conn
	RawConn() net.Conn

	// SetTransferEventListener set a method will be called when connection transfer occur
	SetTransferEventListener(listener func() bool)

	// SetIdleTimeout sets the timeout that will set the connnection to idle. At intervals of readTimeout,
	// Connections can be closed after idle for idleTimeout/readTimeout checks. Mosn close idle connections
	// if no idle timeout set,a zero value for idleTimeout means no idle connections.
	SetIdleTimeout(readTimeout time.Duration, idleTimeout time.Duration)

	// State returns the connection state
	State() ConnState

	// OnRead deals with data not read from doRead process
	OnRead(buffer IoBuffer)
}

Connection interface

type ConnectionCloseType

type ConnectionCloseType string

ConnectionCloseType represent connection close type

const (
	// FlushWrite means write buffer to underlying io then close connection
	FlushWrite ConnectionCloseType = "FlushWrite"
	// NoFlush means close connection without flushing buffer
	NoFlush ConnectionCloseType = "NoFlush"
)

Connection close types

type ConnectionEvent

type ConnectionEvent string

ConnectionEvent type

const (
	RemoteClose     ConnectionEvent = "RemoteClose"
	LocalClose      ConnectionEvent = "LocalClose"
	OnReadErrClose  ConnectionEvent = "OnReadErrClose"
	OnWriteErrClose ConnectionEvent = "OnWriteErrClose"
	OnConnect       ConnectionEvent = "OnConnect"
	Connected       ConnectionEvent = "ConnectedFlag"
	ConnectTimeout  ConnectionEvent = "ConnectTimeout"
	ConnectFailed   ConnectionEvent = "ConnectFailed"
	OnReadTimeout   ConnectionEvent = "OnReadTimeout"
	OnWriteTimeout  ConnectionEvent = "OnWriteTimeout"
	OnShutdown      ConnectionEvent = "OnShutdown"
)

ConnectionEvent types

func (ConnectionEvent) ConnectFailure

func (ce ConnectionEvent) ConnectFailure() bool

ConnectFailure represents whether the event is triggered by connection failure

func (ConnectionEvent) IsClose

func (ce ConnectionEvent) IsClose() bool

IsClose represents whether the event is triggered by connection close

type ConnectionEventListener

type ConnectionEventListener interface {
	// OnEvent is called on ConnectionEvent
	OnEvent(event ConnectionEvent)
}

ConnectionEventListener is a network level callbacks that happen on a connection.

type Decoder

type Decoder interface {
	// Decode decodes binary data to a model
	// pass sub protocol type to identify protocol format
	// return 1. decoded model(nil if no enough data) 2. decode error
	Decode(ctx context.Context, data IoBuffer) (interface{}, error)
}

Decoder is a decoder interface to extend various of protocols

type DirectResponseRule

type DirectResponseRule interface {

	// StatusCode returns the repsonse status code
	StatusCode() int
	// Body returns the response body string
	Body() string
}

DirectResponseRule contains direct response info

type DoRetryCallback

type DoRetryCallback func()

type Driver

type Driver interface {
	Init(config map[string]interface{}) error

	Register(proto ProtocolName, builder TracerBuilder)

	Get(proto ProtocolName) Tracer
}

type DurationConfig

type DurationConfig struct {
	time.Duration
}

DurationConfig ia a wrapper for time.Duration, so time config can be written in '300ms' or '1h' format

func (DurationConfig) MarshalJSON

func (d DurationConfig) MarshalJSON() (b []byte, err error)

MarshalJSON

func (*DurationConfig) UnmarshalJSON

func (d *DurationConfig) UnmarshalJSON(b []byte) (err error)

UnmarshalJSON get DurationConfig.Duration from json file

type Encoder

type Encoder interface {
	// Encode encodes a model to binary data
	// return 1. encoded bytes 2. encode error
	Encode(ctx context.Context, model interface{}) (IoBuffer, error)
}

Encoder is a encoder interface to extend various of protocols

type FactoryInitializer

type FactoryInitializer interface {
	Init(interface{}) error
}

FactoryInitializer represents a filter Factory needs to be inited before called.

type FilterManager

type FilterManager interface {
	// AddReadFilter adds a read filter
	AddReadFilter(rf ReadFilter)

	// AddWriteFilter adds a write filter
	AddWriteFilter(wf WriteFilter)

	// ListReadFilter returns the list of read filters
	ListReadFilter() []ReadFilter

	// ListWriteFilters returns the list of write filters
	ListWriteFilters() []WriteFilter

	// InitializeReadFilters initialize read filters
	InitializeReadFilters() bool

	// OnRead is called on data read
	OnRead()

	// OnWrite is called before data write
	OnWrite(buffer []IoBuffer) FilterStatus
}

FilterManager is a groups of filters

type FilterStatus

type FilterStatus string

FilterStatus type

const (
	Continue FilterStatus = "Continue"
	Stop     FilterStatus = "Stop"
)

FilterStatus types

type GoAwayPredicate

type GoAwayPredicate interface {
	IsGoAwayFrame() bool
}

GoAwayPredicate provides the ability to judge if current is a goaway frmae, which indicates that current connection should be no longer used and turn into the draining state.

type GoAwayer

type GoAwayer interface {
	// GoAway builds an active GoAway command
	GoAway(context context.Context) XFrame
}

GoAwayer provides the ability to construct proper GoAway command for xprotocol, It's better to NOT implement this interface instead of return nil when the protocol doesn't have goaway.

type HTTPMapping

type HTTPMapping interface {
	MappingHeaderStatusCode(ctx context.Context, headers HeaderMap) (int, error)
}

HTTPMapping maps the contents of protocols to HTTP standard

type HashPolicy

type HashPolicy interface {
	GenerateHash(context context.Context) uint64
}

type HeaderMap

type HeaderMap interface {
	// Get value of key
	// If multiple values associated with this key, first one will be returned.
	Get(key string) (string, bool)

	// Set key-value pair in header map, the previous pair will be replaced if exists
	Set(key, value string)

	// Add value for given key.
	// Multiple headers with the same key may be added with this function.
	// Use Set for setting a single header for the given key.
	Add(key, value string)

	// Del delete pair of specified key
	Del(key string)

	// Range calls f sequentially for each key and value present in the map.
	// If f returns false, range stops the iteration.
	Range(f func(key, value string) bool)

	// Clone used to deep copy header's map
	Clone() HeaderMap

	// ByteSize return size of HeaderMap
	ByteSize() uint64
}

HeaderMap is a interface to provide operation facade with user-value headers

type HealthFlag

type HealthFlag int

HealthFlag type

const (
	// The host is currently failing active health checks.
	FAILED_ACTIVE_HC HealthFlag = 0x1
	// The host is currently considered an outlier and has been ejected.
	FAILED_OUTLIER_CHECK HealthFlag = 0x02
)

type HeartbeatPredicate

type HeartbeatPredicate interface {
	IsHeartbeatFrame() bool
}

HeartbeatPredicate provides the ability to judge if current frame is a heartbeat, which is usually used to make connection keepalive

type Heartbeater

type Heartbeater interface {
	// Trigger builds an active heartbeat command
	Trigger(context context.Context, requestId uint64) XFrame

	// Reply builds heartbeat command corresponding to the given requestID
	Reply(context context.Context, request XFrame) XRespFrame
}

HeartbeatBuilder provides the ability to construct proper heartbeat command for xprotocol sub-protocols

type Hijacker

type Hijacker interface {
	// BuildResponse build response with given status code
	Hijack(context context.Context, request XFrame, statusCode uint32) XRespFrame

	// Mapping the http status code, which used by proxy framework into protocol-specific status
	Mapping(httpStatusCode uint32) uint32
}

Hijacker provides the ability to construct proper response command for xprotocol sub-protocols

type HostInfo

type HostInfo interface {
	// Hostname returns the host's name
	Hostname() string

	// Metadata returns the host's meta data
	Metadata() Metadata

	// AddressString retuens the host's address string
	AddressString() string

	// Weight returns the host weight
	Weight() uint32

	// SupportTLS returns whether the host support tls connections or not
	// If returns true, means support tls connection
	SupportTLS() bool

	// ClearHealthFlag clear the input flag
	ClearHealthFlag(flag HealthFlag)

	// ContainHealthFlag checks whether the heatlhy state contains the flag
	ContainHealthFlag(flag HealthFlag) bool

	// SetHealthFlag set the input flag
	SetHealthFlag(flag HealthFlag)

	// HealthFlag returns the current healthy flag
	HealthFlag() HealthFlag

	// Health checks whether the host is healthy or not
	Health() bool
}

HostInfo defines a host's basic information

type IoBuffer

type IoBuffer interface {
	// Read reads the next len(p) bytes from the buffer or until the buffer
	// is drained. The return value n is the number of bytes read. If the
	// buffer has no data to return, err is io.EOF (unless len(p) is zero);
	// otherwise it is nil.
	Read(p []byte) (n int, err error)

	// ReadOnce make a one-shot read and appends it to the buffer, growing
	// the buffer as needed. The return value n is the number of bytes read. Any
	// error except io.EOF encountered during the read is also returned. If the
	// buffer becomes too large, ReadFrom will panic with ErrTooLarge.
	ReadOnce(r io.Reader) (n int64, err error)

	// ReadFrom reads data from r until EOF and appends it to the buffer, growing
	// the buffer as needed. The return value n is the number of bytes read. Any
	// error except io.EOF encountered during the read is also returned. If the
	// buffer becomes too large, ReadFrom will panic with ErrTooLarge.
	ReadFrom(r io.Reader) (n int64, err error)

	// Grow updates the length of the buffer by n, growing the buffer as
	// needed. The return value n is the length of p; err is always nil. If the
	// buffer becomes too large, Write will panic with ErrTooLarge.
	Grow(n int) error

	// Write appends the contents of p to the buffer, growing the buffer as
	// needed. The return value n is the length of p; err is always nil. If the
	// buffer becomes too large, Write will panic with ErrTooLarge.
	Write(p []byte) (n int, err error)

	// WriteString appends the string to the buffer, growing the buffer as
	// needed. The return value n is the length of s; err is always nil. If the
	// buffer becomes too large, Write will panic with ErrTooLarge.
	WriteString(s string) (n int, err error)

	// WriteByte appends the byte to the buffer, growing the buffer as
	// needed. The return value n is the length of s; err is always nil. If the
	// buffer becomes too large, Write will panic with ErrTooLarge.
	WriteByte(p byte) error

	// WriteUint16 appends the uint16 to the buffer, growing the buffer as
	// needed. The return value n is the length of s; err is always nil. If the
	// buffer becomes too large, Write will panic with ErrTooLarge.
	WriteUint16(p uint16) error

	// WriteUint32 appends the uint32 to the buffer, growing the buffer as
	// needed. The return value n is the length of s; err is always nil. If the
	// buffer becomes too large, Write will panic with ErrTooLarge.
	WriteUint32(p uint32) error

	// WriteUint64 appends the uint64 to the buffer, growing the buffer as
	// needed. The return value n is the length of s; err is always nil. If the
	// buffer becomes too large, Write will panic with ErrTooLarge.
	WriteUint64(p uint64) error

	// WriteTo writes data to w until the buffer is drained or an error occurs.
	// The return value n is the number of bytes written; it always fits into an
	// int, but it is int64 to match the io.WriterTo interface. Any error
	// encountered during the write is also returned.
	WriteTo(w io.Writer) (n int64, err error)

	// Peek returns n bytes from buffer, without draining any buffered data.
	// If n > readable buffer, nil will be returned.
	// It can be used in codec to check first-n-bytes magic bytes
	// Note: do not change content in return bytes, use write instead
	Peek(n int) []byte

	// Bytes returns all bytes from buffer, without draining any buffered data.
	// It can be used to get fixed-length content, such as headers, body.
	// Note: do not change content in return bytes, use write instead
	Bytes() []byte

	// Drain drains a offset length of bytes in buffer.
	// It can be used with Bytes(), after consuming a fixed-length of data
	Drain(offset int)

	// Len returns the number of bytes of the unread portion of the buffer;
	// b.Len() == len(b.Bytes()).
	Len() int

	// Cap returns the capacity of the buffer's underlying byte slice, that is, the
	// total space allocated for the buffer's data.
	Cap() int

	// Reset resets the buffer to be empty,
	// but it retains the underlying storage for use by future writes.
	Reset()

	// Clone makes a copy of IoBuffer struct
	Clone() IoBuffer

	// String returns the contents of the unread portion of the buffer
	// as a string. If the Buffer is a nil pointer, it returns "<nil>".
	String() string

	// Alloc alloc bytes from BytePoolBuffer
	Alloc(int)

	// Free free bytes to BytePoolBuffer
	Free()

	// Count sets and returns reference count
	Count(int32) int32

	// EOF returns whether Io is EOF on the connection
	EOF() bool

	//SetEOF sets the IoBuffer EOF
	SetEOF(eof bool)

	Append(data []byte) error

	CloseWithError(err error)
}

type KeyValueMatchCriteria

type KeyValueMatchCriteria interface {
	Get(i int) KeyValueMatchCriterion
	Len() int
	Range(f func(KeyValueMatchCriterion) bool)
}

type KeyValueMatchCriterion

type KeyValueMatchCriterion interface {
	Key() string
	MatchType() KeyValueMatchType
	Matcher() string
}

type KeyValueMatchType

type KeyValueMatchType uint32

KeyValueMatchType defines the header or query param match pattern

const (
	ValueExact KeyValueMatchType = iota
	ValueRegex
)

Key value match patterns

type ListenerFilterChainFactory

type ListenerFilterChainFactory interface {
	OnAccept(callbacks ListenerFilterChainFactoryCallbacks) FilterStatus
}

ListenerFilterChainFactory adds filter into ListenerFilterChainFactoryCallbacks

func CreateListenerFilterChainFactory

func CreateListenerFilterChainFactory(filterType string, config map[string]interface{}) (ListenerFilterChainFactory, error)

CreateListenerFilterChainFactory creates a ListenerFilterChainFactory according to filterType

type ListenerFilterChainFactoryCallbacks

type ListenerFilterChainFactoryCallbacks interface {
	// Conn returns the Connection reference used in callback handler
	Conn() net.Conn
	ContinueFilterChain(ctx context.Context, success bool)
	// SetOriginalAddr sets the original ip and port
	SetOriginalAddr(ip string, port int)
	// Set useOriginalDst
	SetUseOriginalDst(flag bool)
	// Get useOriginalDst
	GetUseOriginalDst() bool
	// Get Context
	GetOriContext() context.Context
	// Accept again
	UseOriginalDst(ctx context.Context)
}

ListenerFilterChainFactoryCallbacks is a wrapper of FilterManager that called in NetworkFilterChainFactory

type ListenerFilterFactoryCreator

type ListenerFilterFactoryCreator func(config map[string]interface{}) (ListenerFilterChainFactory, error)

ListenerFilterFactoryCreator creates a ListenerFilterChainFactory according to config

type MatchResult

type MatchResult int

MatchResult

const (
	MatchFailed MatchResult = iota
	MatchSuccess
	MatchAgain
)

type Matchable

type Matchable interface {
	Match(ctx context.Context, headers HeaderMap) Route
}

type Metadata

type Metadata map[string]string

Metadata field can be used to provide additional information about the route. It can be used for configuration, stats, and logging. The metadata should go under the filter namespace that will need it.

type MetadataMatchCriteria

type MetadataMatchCriteria interface {
	// @return: a set of MetadataMatchCriterion(metadata) sorted lexically by name
	// to be matched against upstream endpoints when load balancing
	MetadataMatchCriteria() []MetadataMatchCriterion

	MergeMatchCriteria(metadataMatches map[string]string) MetadataMatchCriteria
}

type MetadataMatchCriterion

type MetadataMatchCriterion interface {
	// the name of the metadata key
	MetadataKeyName() string

	// the value for the metadata key
	MetadataValue() string
}

type Metrics added in v1.2.0

type Metrics interface {
	// Type returns metrics logical type, e.g. 'downstream'/'upstream', this is more like the Subsystem concept
	Type() string

	// Labels used to distinguish the metrics' owner for same metrics key set, like 'cluster: local_service'
	Labels() map[string]string

	// SortedLabels return keys and vals in stable order
	SortedLabels() (keys, vals []string)

	// Counter creates or returns a go-metrics counter by key
	// if the key is registered by other interface, it will be panic
	Counter(key string) metrics.Counter

	// Gauge creates or returns a go-metrics gauge by key
	// if the key is registered by other interface, it will be panic
	Gauge(key string) metrics.Gauge

	// Histogram creates or returns a go-metrics histogram by key
	// if the key is registered by other interface, it will be panic
	Histogram(key string) metrics.Histogram

	// EWMA creates or returns a go-metrics ewma by key
	// if the key is registered by other interface, it will be panic.
	// See: https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
	EWMA(key string, alpha float64) metrics.EWMA

	// Each call the given function for each registered metric.
	Each(func(string, interface{}))

	// UnregisterAll unregister all metrics.  (Mostly for testing.)
	UnregisterAll()
}

Metrics is a wrapper interface for go-metrics support Counter, Gauge, Histogram, EWMA

type MetricsSink added in v1.2.0

type MetricsSink interface {
	// Flush flush given metrics
	Flush(writer io.Writer, metrics []Metrics)
}

MetricsSink flush metrics to backend storage

type MirrorPolicy

type MirrorPolicy interface {
	ClusterName() string
	IsMirror() bool
}

type Multiplexing

type Multiplexing interface {
	GetRequestId() uint64

	SetRequestId(id uint64)
}

Multiplexing provides the ability to distinguish multi-requests in single-connection by recognize 'request-id' semantics

type NetWorkFilterChainFactoryCallbacks

type NetWorkFilterChainFactoryCallbacks interface {
	AddReadFilter(rf ReadFilter)
	AddWriteFilter(wf WriteFilter)
}

NetWorkFilterChainFactoryCallbacks is a wrapper of FilterManager that called in NetworkFilterChainFactory

type NetworkFilterChainFactory

type NetworkFilterChainFactory interface {
	CreateFilterChain(context context.Context, callbacks NetWorkFilterChainFactoryCallbacks)
}

NetworkFilterChainFactory adds filter into NetWorkFilterChainFactoryCallbacks

func CreateNetworkFilterChainFactory

func CreateNetworkFilterChainFactory(filterType string, config map[string]interface{}) (NetworkFilterChainFactory, error)

CreateNetworkFilterChainFactory creates a NetworkFilterChainFactory according to filterType

type NetworkFilterFactoryCreator

type NetworkFilterFactoryCreator func(config map[string]interface{}) (NetworkFilterChainFactory, error)

NetworkFilterFactoryCreator creates a NetworkFilterChainFactory according to config

type PathMatchCriterion

type PathMatchCriterion interface {
	MatchType() PathMatchType
	Matcher() string
}

type PathMatchType

type PathMatchType uint32

PathMatchType defines the path match pattern

const (
	None PathMatchType = iota
	Prefix
	Exact
	Regex
	RPCHeader
	Variable
)

Path match patterns

type Policy

type Policy interface {
	RetryPolicy() RetryPolicy

	ShadowPolicy() ShadowPolicy

	HashPolicy() HashPolicy

	MirrorPolicy() MirrorPolicy
}

Policy defines a group of route policy

type PoolMode

type PoolMode int

PoolMode is whether PingPong or multiplex

const (
	PingPong PoolMode = iota
	Multiplex
	TCP
)

type Protocol

type Protocol interface {
	// Encoder is the encoder implementation of the protocol
	Encoder
	// Decoder is the decoder implementation of the protocol
	Decoder
	// Name is the  name of the protocol
	Name() ProtocolName
}

Protocol need to provides ability to convert mode-to-binary and vice-versa

type ProtocolEngine

type ProtocolEngine interface {
	// Match use registered matchFunc to recognize corresponding protocol
	Match(ctx context.Context, data IoBuffer) (Protocol, MatchResult)
	// Register register encoder and decoder, which recognized by the matchFunc
	Register(matchFunc ProtocolMatch, protocol Protocol) error
}

ProtocolEngine is a protocols' facade used by Stream, it provides auto protocol detection by the ProtocolMatch func

type ProtocolMatch

type ProtocolMatch func(data []byte) MatchResult

ProtocolMatch recognize if the given data matches the protocol specification or not

type ProtocolName

type ProtocolName string

type ProtocolResourceName

type ProtocolResourceName string
const (
	// full uri contains path + args
	URI ProtocolResourceName = "URI"
	// only path not contains args
	PATH ProtocolResourceName = "PATH"
	// only arguments
	ARG ProtocolResourceName = "ARG"

	SCHEME ProtocolResourceName = "scheme"
	HEADER ProtocolResourceName = "header"
	COOKIE ProtocolResourceName = "cookie"
)

protocol resource name

type ReadFilter

type ReadFilter interface {
	// OnData is called everytime bytes is read from the connection
	OnData(buffer IoBuffer) FilterStatus

	// OnNewConnection is called on new connection is created
	OnNewConnection() FilterStatus

	// InitializeReadFilterCallbacks initials read filter callbacks. It used by init read filter
	InitializeReadFilterCallbacks(cb ReadFilterCallbacks)
}

ReadFilter is a connection binary read filter, registered by FilterManager.AddReadFilter

type ReadFilterCallbacks

type ReadFilterCallbacks interface {
	// Connection returns the connection triggered the callback
	Connection() Connection

	// ContinueReading filter iteration on filter stopped, next filter will be called with current read buffer
	ContinueReading()

	// UpstreamHost returns current selected upstream host.
	UpstreamHost() HostInfo

	// SetUpstreamHost set currently selected upstream host.
	SetUpstreamHost(upstreamHost HostInfo)
}

ReadFilterCallbacks is called by read filter to talk to connection

type ReceiverFilterPhase

type ReceiverFilterPhase int
const (
	BeforeRoute ReceiverFilterPhase = iota
	AfterRoute
	AfterChooseHost
)

type RedirectRule

type RedirectRule interface {
	// RedirectCode returns the redirect repsonse status code
	RedirectCode() int
	// RedirectPath returns the path that will overwrite the current path
	RedirectPath() string
	// RedirectHost returns the host that will overwrite the current host
	RedirectHost() string
	// RedirectScheme returns the scheme that will overwrite the current scheme
	RedirectScheme() string
}

RedirectRule contains redirect info

type RequestInfo

type RequestInfo interface {
	// StartTime returns the time that request arriving
	StartTime() time.Time

	// SetStartTime sets StartTime
	SetStartTime()

	// RequestReceivedDuration returns duration between request arriving and request forwarding to upstream
	RequestReceivedDuration() time.Duration

	// SetRequestReceivedDuration sets duration between request arriving and request forwarding to upstream
	SetRequestReceivedDuration(time time.Time)

	// ResponseReceivedDuration gets duration between request arriving and response received
	ResponseReceivedDuration() time.Duration

	// SetResponseReceivedDuration sets duration between request arriving and response received
	SetResponseReceivedDuration(time time.Time)

	// RequestFinishedDuration returns duration between request arriving and request finished
	RequestFinishedDuration() time.Duration

	// SetRequestFinishedDuration sets duration between request arriving and request finished
	SetRequestFinishedDuration(time time.Time)

	// SetProcessTimeDuration sets duration in mosn
	SetProcessTimeDuration(d time.Duration)

	// ProcessTimeDuration returns duration between mosn
	ProcessTimeDuration() time.Duration

	// BytesSent reports the bytes sent
	BytesSent() uint64

	// SetBytesSent sets the bytes sent
	SetBytesSent(bytesSent uint64)

	// BytesReceived reports the bytes received
	BytesReceived() uint64

	// SetBytesReceived sets the bytes received
	SetBytesReceived(bytesReceived uint64)

	// Protocol returns the request's protocol type
	Protocol() ProtocolName
	// SetProtocol sets the request's protocol type
	SetProtocol(p ProtocolName)

	// ResponseCode reports the request's response code
	// The code is http standard status code.
	ResponseCode() int

	// SetResponseCode set request's response code
	// Mosn use http standard status code for log, if a protocol have different status code
	// we will try to mapping it to http status code, and log it
	SetResponseCode(code int)

	// Duration reports the duration since request's starting time
	Duration() time.Duration

	// GetResponseFlag gets request's response flag
	GetResponseFlag(flag ResponseFlag) bool

	// SetResponseFlag sets request's response flag
	SetResponseFlag(flag ResponseFlag)

	//UpstreamHost reports  the selected upstream's host information
	UpstreamHost() HostInfo

	// OnUpstreamHostSelected sets the selected upstream's host information
	OnUpstreamHostSelected(host HostInfo)

	// UpstreamLocalAddress reports the upstream's local network address
	UpstreamLocalAddress() string

	// SetUpstreamLocalAddress sets upstream's local network address
	SetUpstreamLocalAddress(localAddress string)

	// IsHealthCheck checks whether the request is health.
	IsHealthCheck() bool

	// SetHealthCheck sets the request's health state.
	SetHealthCheck(isHc bool)

	// DownstreamLocalAddress reports the downstream's local network address.
	DownstreamLocalAddress() net.Addr

	// SetDownstreamLocalAddress sets the downstream's local network address.
	SetDownstreamLocalAddress(addr net.Addr)

	// DownstreamRemoteAddress reports the downstream's remote network address.
	DownstreamRemoteAddress() net.Addr

	// SetDownstreamRemoteAddress sets the downstream's remote network address.
	SetDownstreamRemoteAddress(addr net.Addr)

	// RouteEntry reports the route rule
	RouteEntry() RouteRule

	// SetRouteEntry sets the route rule
	SetRouteEntry(routerRule RouteRule)
}

RequestInfo has information for a request, include the basic information, the request's downstream information, ,the request's upstream information and the router information.

type ResponseFlag

type ResponseFlag int

ResponseFlag type

const (
	// no healthy upstream found
	NoHealthyUpstream ResponseFlag = 0x2
	// Upstream Request timeout
	UpstreamRequestTimeout ResponseFlag = 0x4
	// local reset
	UpstreamLocalReset ResponseFlag = 0x8
	// upstream reset
	UpstreamRemoteReset ResponseFlag = 0x10
	// connect upstream failure
	UpstreamConnectionFailure ResponseFlag = 0x20
	// upstream terminate connection
	UpstreamConnectionTermination ResponseFlag = 0x40
	// upstream's connection overflow
	UpstreamOverflow ResponseFlag = 0x80
	// no route found
	NoRouteFound ResponseFlag = 0x100
	// inject delay
	DelayInjected ResponseFlag = 0x200
	// inject fault
	FaultInjected ResponseFlag = 0x400
	// rate limited
	RateLimited ResponseFlag = 0x800
	// payload limit
	ReqEntityTooLarge ResponseFlag = 0x1000
	// downstream terminated
	DownStreamTerminate ResponseFlag = 0x2000
)

Some Response Flags

type RetryCheckStatus

type RetryCheckStatus int

RetryCheckStatus type

const (
	ShouldRetry   RetryCheckStatus = 0
	NoRetry       RetryCheckStatus = -1
	RetryOverflow RetryCheckStatus = -2
)

RetryCheckStatus types

type RetryPolicy

type RetryPolicy interface {
	RetryOn() bool

	TryTimeout() time.Duration

	NumRetries() uint32

	RetryableStatusCodes() []uint32
}

RetryPolicy is a type of Policy

type RetryState

type RetryState interface {
	Enabled() bool

	ShouldRetry(respHeaders map[string]string, resetReson string, doRetryCb DoRetryCallback) bool
}

type Route

type Route interface {
	// RouteRule returns the route rule
	RouteRule() RouteRule

	// DirectResponseRule returns direct response rule
	DirectResponseRule() DirectResponseRule

	// RedirectRule returns redirect rule
	RedirectRule() RedirectRule
}

Route is a route instance

type RouteBase

type RouteBase interface {
	Route
	Matchable
}

type RouteRule

type RouteRule interface {
	// VirtualHost returns the virtual host that owns the route
	VirtualHost() VirtualHost

	// ClusterName returns the route's cluster name
	ClusterName(ctx context.Context) string

	// UpstreamProtocol returns the protocol that route's cluster supported
	// If it is configured, the protocol will replace the proxy config's upstream protocol
	UpstreamProtocol() string

	// GlobalTimeout returns the global timeout
	GlobalTimeout() time.Duration

	// Policy returns the route's route policy
	Policy() Policy

	// MetadataMatchCriteria returns the metadata that a subset load balancer should match when selecting an upstream host
	// as we may use weighted cluster's metadata, so need to input cluster's name
	MetadataMatchCriteria(clusterName string) MetadataMatchCriteria

	// PerFilterConfig returns per filter config from xds
	PerFilterConfig() map[string]interface{}

	// FinalizeRequestHeaders do potentially destructive header transforms on request headers prior to forwarding
	FinalizeRequestHeaders(ctx context.Context, headers HeaderMap, requestInfo RequestInfo)

	// FinalizeResponseHeaders do potentially destructive header transforms on response headers prior to forwarding
	FinalizeResponseHeaders(ctx context.Context, headers HeaderMap, requestInfo RequestInfo)

	// PathMatchCriterion returns the route's PathMatchCriterion
	PathMatchCriterion() PathMatchCriterion

	// HeaderMatchCriteria returns the route's HeaderMatchCriteria
	HeaderMatchCriteria() KeyValueMatchCriteria
}

RouteRule defines parameters for a route

type SenderFilterPhase

type SenderFilterPhase int
const (
	BeforeSend SenderFilterPhase = iota
)

type ServiceAware

type ServiceAware interface {
	GetServiceName() string

	GetMethodName() string
}

ServiceAware provides the ability to get the most common info for rpc invocation: service name and method name

type ShadowPolicy

type ShadowPolicy interface {
	ClusterName() string

	RuntimeKey() string
}

ShadowPolicy is a type of Policy

type Span

type Span interface {
	TraceId() string

	SpanId() string

	ParentSpanId() string

	SetOperation(operation string)

	SetTag(key uint64, value string)

	SetRequestInfo(requestInfo RequestInfo)

	Tag(key uint64) string

	FinishSpan()

	InjectContext(requestHeaders HeaderMap, requestInfo RequestInfo)

	SpawnChild(operationName string, startTime time.Time) Span
}

type StreamFilterBase

type StreamFilterBase interface {
	OnDestroy()
}

type StreamFilterChainFactory

type StreamFilterChainFactory interface {
	CreateFilterChain(context context.Context, callbacks StreamFilterChainFactoryCallbacks)
}

StreamFilterChainFactory adds filter into callbacks

func CreateStreamFilterChainFactory

func CreateStreamFilterChainFactory(filterType string, config map[string]interface{}) (StreamFilterChainFactory, error)

CreateStreamFilterChainFactory creates a StreamFilterChainFactory according to filterType

type StreamFilterChainFactoryCallbacks

type StreamFilterChainFactoryCallbacks interface {
	AddStreamSenderFilter(filter StreamSenderFilter, p SenderFilterPhase)

	AddStreamReceiverFilter(filter StreamReceiverFilter, p ReceiverFilterPhase)

	// add access log per stream
	AddStreamAccessLog(accessLog AccessLog)
}

StreamFilterChainFactoryCallbacks is called in StreamFilterChainFactory

type StreamFilterFactoryCreator

type StreamFilterFactoryCreator func(config map[string]interface{}) (StreamFilterChainFactory, error)

StreamFilterFactoryCreator creates a StreamFilterChainFactory according to config

type StreamFilterHandler

type StreamFilterHandler interface {
	// Route returns a route for current stream
	Route() Route

	// RequestInfo returns request info related to the stream
	RequestInfo() RequestInfo

	// Connection returns the originating connection
	Connection() Connection
}

StreamFilterHandler is called by stream filter to interact with underlying stream

type StreamFilterStatus

type StreamFilterStatus string
const (
	// Continue filter chain iteration.
	StreamFilterContinue StreamFilterStatus = "Continue"
	// Do not iterate to next iterator.
	StreamFilterStop StreamFilterStatus = "Stop"
	// terminate request.
	StreamFiltertermination StreamFilterStatus = "termination"

	StreamFilterReMatchRoute StreamFilterStatus = "Retry Match Route"
	StreamFilterReChooseHost StreamFilterStatus = "Retry Choose Host"
)

StreamFilterStatus types

type StreamReceiverFilter

type StreamReceiverFilter interface {
	StreamFilterBase

	// OnReceive is called with decoded request/response
	OnReceive(ctx context.Context, headers HeaderMap, buf IoBuffer, trailers HeaderMap) StreamFilterStatus

	// SetReceiveFilterHandler sets decoder filter callbacks
	SetReceiveFilterHandler(handler StreamReceiverFilterHandler)
}

StreamReceiverFilter is a StreamFilterBase wrapper

type StreamReceiverFilterHandler

type StreamReceiverFilterHandler interface {
	StreamFilterHandler

	// AppendHeaders is called with headers to be encoded, optionally indicating end of stream
	// Filter uses this function to send out request/response headers of the stream
	// endStream supplies whether this is a header only request/response
	AppendHeaders(headers HeaderMap, endStream bool)

	// AppendData is called with data to be encoded, optionally indicating end of stream.
	// Filter uses this function to send out request/response data of the stream
	// endStream supplies whether this is the last data
	AppendData(buf IoBuffer, endStream bool)

	// AppendTrailers is called with trailers to be encoded, implicitly ends the stream.
	// Filter uses this function to send out request/response trailers of the stream
	AppendTrailers(trailers HeaderMap)

	// SendHijackReply is called when the filter will response directly
	SendHijackReply(code int, headers HeaderMap)

	// SendHijackReplyWithBody is called when the filter will response directly with body
	SendHijackReplyWithBody(code int, headers HeaderMap, body string)

	// SendDirectRespoonse is call when the filter will response directly
	SendDirectResponse(headers HeaderMap, buf IoBuffer, trailers HeaderMap)

	// TerminateStream can force terminate a request asynchronously.
	// The response status code should be HTTP status code.
	// If the request is already finished, returns false.
	TerminateStream(code int) bool

	// TODO: remove all of the following when proxy changed to single request @lieyuan
	// StreamFilters will modified headers/data/trailer in different steps
	// for example, maybe modify headers in on receive data
	GetRequestHeaders() HeaderMap
	SetRequestHeaders(headers HeaderMap)

	GetRequestData() IoBuffer
	SetRequestData(buf IoBuffer)

	GetRequestTrailers() HeaderMap
	SetRequestTrailers(trailers HeaderMap)

	// GetFilterCurrentPhase get current phase for filter
	GetFilterCurrentPhase() ReceiverFilterPhase
}

StreamReceiverFilterHandler add additional callbacks that allow a decoding filter to restart decoding if they decide to hold data

type StreamSenderFilter

type StreamSenderFilter interface {
	StreamFilterBase

	// Append encodes request/response
	Append(ctx context.Context, headers HeaderMap, buf IoBuffer, trailers HeaderMap) StreamFilterStatus

	// SetSenderFilterHandler sets the StreamSenderFilterHandler
	SetSenderFilterHandler(handler StreamSenderFilterHandler)
}

StreamSenderFilter is a stream sender filter

type StreamSenderFilterHandler

type StreamSenderFilterHandler interface {
	StreamFilterHandler

	// TODO :remove all of the following when proxy changed to single request @lieyuan
	// StreamFilters will modified headers/data/trailer in different steps
	// for example, maybe modify headers in AppendData
	GetResponseHeaders() HeaderMap
	SetResponseHeaders(headers HeaderMap)

	GetResponseData() IoBuffer
	SetResponseData(buf IoBuffer)

	GetResponseTrailers() HeaderMap
	SetResponseTrailers(trailers HeaderMap)
}

StreamSenderFilterHandler is a StreamFilterHandler wrapper

type StreamType

type StreamType int

StreamType distinguish the stream flow type. Request: stream is a normal request and needs response RequestOneWay: stream is a oneway request and doesn't need response Response: stream is a response to specific request

const (
	Request StreamType = iota
	RequestOneWay
	Response
)

type Tracer

type Tracer interface {
	Start(ctx context.Context, request interface{}, startTime time.Time) Span
}

type TracerBuilder

type TracerBuilder func(config map[string]interface{}) (Tracer, error)

factory

type VirtualHost

type VirtualHost interface {
	Name() string

	// GetRouteFromEntries returns a Route matched the condition
	GetRouteFromEntries(ctx context.Context, headers HeaderMap) Route

	// GetAllRoutesFromEntries returns all Route matched the condition
	GetAllRoutesFromEntries(ctx context.Context, headers HeaderMap) []Route

	// GetRouteFromHeaderKV is used to quickly locate and obtain routes in certain scenarios
	GetRouteFromHeaderKV(key, value string) Route

	// AddRoute adds a new route into virtual host
	AddRoute(route RouteBase) error

	// RemoveAllRoutes clear all the routes in the virtual host
	RemoveAllRoutes()

	// PerFilterConfig returns per filter config from xds
	PerFilterConfig() map[string]interface{}

	// FinalizeRequestHeaders do potentially destructive header transforms on request headers prior to forwarding
	FinalizeRequestHeaders(ctx context.Context, headers HeaderMap, requestInfo RequestInfo)

	// FinalizeResponseHeaders do potentially destructive header transforms on response headers prior to forwarding
	FinalizeResponseHeaders(ctx context.Context, headers HeaderMap, requestInfo RequestInfo)
}

VirtualHost definition.

type WriteFilter

type WriteFilter interface {
	// OnWrite is called before data write to raw connection
	OnWrite(buffer []IoBuffer) FilterStatus
}

WriteFilter is a connection binary write filter, only called by conn accept loop

type XDSConfigHandler added in v1.1.0

type XDSConfigHandler func(s *any.Any) (map[string]interface{}, error)

XDSConfigHandler converts a map according to any.Any

type XFrame

type XFrame interface {
	// TODO: make multiplexing optional, and maybe we can support PING-PONG protocol in this framework.
	Multiplexing

	HeartbeatPredicate

	// GetTimeout returns a number means Milliseconds for protocol timeout
	// If no timeout defines, returns zero means default timeout
	// If returns a negative number, means never timeout
	GetTimeout() int32

	GetStreamType() StreamType

	GetHeader() HeaderMap

	GetData() IoBuffer

	SetData(data IoBuffer)
}

XFrame represents the minimal programmable object of the protocol.

type XProtocol

type XProtocol interface {
	Protocol

	Heartbeater

	Hijacker

	PoolMode() PoolMode // configure this to use which connpool

	EnableWorkerPool() bool // same meaning as EnableWorkerPool in types.StreamConnection

	// generate a request id for stream to combine stream request && response
	// use connection param as base
	GenerateRequestID(*uint64) uint64
}

XProtocol provides extra ability(Heartbeater, Hijacker) to interacts with the proxy framework based on the Protocol interface. e.g. A request which cannot find route should be responded with a error response like '404 Not Found', that is what Hijacker interface exactly provides.

type XProtocolCodec

type XProtocolCodec interface {
	ProtocolName() ProtocolName

	// If a protocol is stateless, the NewXProtocol is recommended return a singleton.
	// If a protocol is stateful, the NewXProtocol create a protocol instance for each connection.
	// The context.Context can provide some configuartion for create protocol instance.
	NewXProtocol(context.Context) XProtocol

	ProtocolMatch() ProtocolMatch

	HTTPMapping() HTTPMapping
}

type XRespFrame

type XRespFrame interface {
	XFrame

	GetStatusCode() uint32
}

XRespFrame expose response status code based on the XFrame

Directories

Path Synopsis
extensions

Jump to

Keyboard shortcuts

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