gonvoy

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2024 License: MIT Imports: 21 Imported by: 0

README

Gonvoy

Go Reference Go Report Card Test Codecov

A thin Go framework to write an HTTP Filter extension on Envoy Proxy. It leverages the Envoy HTTP Golang Filter as its foundation.

Features

  • Full Go experience for building Envoy HTTP Filter extension.

  • Porting net/http interface experience to extend Envoy Proxy behavior with HTTP Golang Filter.

  • Logging with go-logr.

  • Stats support; Enabling users to generate their own custom metrics.

  • Panic-free support; If a panic does occur, it is ensured that it won't break the user experience, particularly the Envoy proxy processes, as it will be handled in a graceful manner by returning a configurable response, defaults to 500.

Compatibility Matrix
Gonvoy Envoy Proxy
v0.1 v1.27
v0.2 v1.29
v0.3 v1.29
latest v1.30

Installation

go get github.com/ardikabs/gonvoy

Development Guide

Prerequisites
Setup
  • Install Git.

  • Install Go 1.22.

  • Clone the project.

    git clone -b plugin git@github.com:ardkabs/gonvoy.git
    
  • Create a meaningful branch

    git checkout -b <your-meaningful-branch>
    
  • Test your changes.

    make test
    
  • We highly recommend instead of only run test, please also do audit which include formatting, linting, vetting, and testing.

    make audit
    
  • Add, commit, and push changes to repository

    git add .
    git commit -s -m "<conventional commit style>"
    git push origin <your-meaningful-branch>
    

    For writing commit message, please use conventionalcommits as a reference.

  • Create a Pull Request (PR). In your PR's description, please explain the goal of the PR and its changes.

Testing
Unit Test
make test
Try It

To try this framework in action, heads to example directory.

License

MIT

Documentation

Index

Constants

View Source
const (
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderXRequestBodyAccess  = "X-Request-Body-Access"
	HeaderXResponseBodyAccess = "X-Response-Body-Access"
	HeaderXContentOperation   = "X-Content-Operation"

	// Values of X-Request-Body-Access and X-Response-Body-Access
	XRequestBodyAccessOff  = "Off"
	XResponseBodyAccessOff = "Off"

	// Values of X-Content-Operation
	ContentOperationReadOnly  = "ReadOnly"
	ContentOperationRO        = "RO" // an initial from ReadOnly
	ContentOperationReadWrite = "ReadWrite"
	ContentOperationRW        = "RW" // an initial from ReadWrite

	// MIME types
	MIMEApplicationJSON            = "application/json"
	MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationXML             = "application/xml"
	MIMEApplicationXMLCharsetUTF8  = MIMEApplicationXML + "; " + charsetUTF8
	MIMEApplicationGRPC            = "application/grpc"
	MIMETextXML                    = "text/xml"
	MIMETextXMLCharsetUTF8         = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm            = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf        = "application/protobuf"
	MIMEApplicationMsgpack         = "application/msgpack"
	MIMETextHTML                   = "text/html"
	MIMETextHTMLCharsetUTF8        = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                  = "text/plain"
	MIMETextPlainCharsetUTF8       = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm              = "multipart/form-data"
	MIMEOctetStream                = "application/octet-stream"
)

Variables

View Source
var (
	// List of errors related to HTTP operations.
	//
	ErrInternalServer      = errors.New("Internal Server Error")
	ErrBadRequest          = errors.New("Bad Request")
	ErrUnauthorized        = errors.New("Unauthorized")
	ErrAccessDenied        = errors.New("Access Denied")
	ErrClientClosedRequest = errors.New("Client Closed Request")

	// List of errors related to runtime operations.
	//
	ErrRuntime               = errors.New("an unexpected runtime error occurred")
	ErrOperationNotPermitted = errors.New("operation not permitted")
	ErrIncompatibleReceiver  = errors.New("receiver and value has an incompatible type")
	ErrNilReceiver           = errors.New("receiver shouldn't be nil")
)
View Source
var (
	DefaultResponseCodeDetailInfo         = ResponseCodeDetailPrefix("goext_info")
	DefaultResponseCodeDetailUnauthorized = ResponseCodeDetailPrefix("goext_unauthorized")
	DefaultResponseCodeDetailAccessDenied = ResponseCodeDetailPrefix("goext_access_denied")
	DefaultResponseCodeDetailError        = ResponseCodeDetailPrefix("goext_error")

	DefaultResponseCodeDetails = DefaultResponseCodeDetailInfo.Wrap("via_Go_extension")
)
View Source
var NoOpHttpFilter = &api.PassThroughStreamFilter{}

Functions

func DefaultErrorHandler

func DefaultErrorHandler(c Context, err error) api.StatusType

DefaultErrorHandler is a default error handler if no custom error handler is provided.

func DefaultRender

func DefaultRender(keysAndValues []interface{}) []interface{}

DefaultRender is a default renderer for key-value zerolog fields that supports logr.Marshaler and fmt.Stringer.

func MustGetProperty

func MustGetProperty(c RuntimeContext, name, defaultVal string) string

MustGetProperty retrieves the value of a property with the given name from the provided RuntimeContext. If the property is not found, it returns the default value. If an error occurs during retrieval, it panics.

func NewGatewayHeaders

func NewGatewayHeaders(keysAndValues ...string) http.Header

func NewGatewayHeadersWithEnvoyHeader

func NewGatewayHeadersWithEnvoyHeader(envoyheader Header, keysAndValues ...string) http.Header

func NewMinimalJSONResponse

func NewMinimalJSONResponse(code, message string, errs ...error) []byte

NewMinimalJSONResponse creates a minimal JSON response with the given code, message, and optional errors. It returns the JSON response as a byte slice.

func RunHttpFilter

func RunHttpFilter(filterName string, filterFactoryFunc HttpFilterFactory, options ConfigOptions)

RunHttpFilter is an entrypoint for onboarding User's HTTP filters at runtime. It must be declared inside `func init()` blocks in main package. Example usage:

package main
func init() {
	RunHttpFilter(filterName, filterFactory, ConfigOptions{
		BaseConfig: new(UserHttpFilterConfig),
	})
}

Types

type Body

type Body interface {
	io.Writer

	// Bytes returns the body content as a byte slice.
	Bytes() []byte

	// WriteString writes a string to the body and returns the number of bytes written and any error encountered.
	WriteString(s string) (n int, err error)

	// String returns the body content as a string.
	String() string
}

Body represents the body of an HTTP request or response.

type Cache

type Cache interface {
	// Store allows you to save a value of any type under a key of any type.
	//
	// Please use caution! The Store function overwrites any existing data.
	Store(key, value any)

	// Load retrieves a value associated with a specific key and assigns it to the receiver.
	//
	// It returns true if a compatible value is successfully loaded,
	// false if no value is found, or an error occurs during the process.
	//
	// If the receiver is not a pointer to the stored data type,
	// Load will return an ErrIncompatibleReceiver.
	//
	// Example usage:
	//   type mystruct struct{}
	//
	//   data := new(mystruct)
	//   cache.Store("keyName", data)
	//
	//   receiver := new(mystruct)
	//   _, _ = cache.Load("keyName", &receiver)
	Load(key, receiver any) (ok bool, err error)
}

Cache is an interface that defines methods for storing and retrieving data in an internal cache. It is designed to maintain data persistently throughout Envoy's lifespan.

type ConfigOptions

type ConfigOptions struct {
	// FilterConfig represents the filter configuration.
	FilterConfig interface{}

	// AlwaysUseChildConfig intend to disable merge behavior, ensuring that it always references the child filter configuration.
	//
	AlwaysUseChildConfig bool

	// IgnoreMergeError specifies during a merge error, instead of panicking, it will fallback to the root configuration.
	//
	IgnoreMergeError bool

	// MetricsPrefix specifies the prefix used for metrics.
	MetricsPrefix string

	// AutoReloadRoute specifies whether the route should be auto reloaded when the request headers changes.
	// It recommends to set this to true when the filter is used in a route configuration and the route is expected to change dynamically within certain conditions.
	AutoReloadRoute bool

	// DisableStrictBodyAccess specifies whether HTTP body access follows strict rules.
	// As its name goes, it defaults to strict, which mean that HTTP body access and manipulation is only possible
	// with the presence of the `X-Content-Operation` header, with accepted values being `ReadOnly` and `ReadWrite`.
	// Even when disabled, users must explicitly enable body access, either for a Request or Response, to carry out operations.
	// See EnableRequestRead, EnableRequestWrite, EnableResponseRead, EnableRequestWrite variables.
	//
	DisableStrictBodyAccess bool

	// EnableRequestBodyRead specifies whether an HTTP Request Body can be accessed.
	// It defaults to false, meaning any operation on OnRequestBody will be ignored.
	// When enabled, operations on OnRequestBody are allowed,
	// but attempts to modify the HTTP Request body will result in a panic, which returns with 502 (Bad Gateway).
	//
	// Warning! Use this option only when necessary, as enabling it is equivalent to granting access
	// to potentially sensitive information that shouldn't be visible to the middleware otherwise.
	EnableRequestBodyRead bool

	// EnableRequestBodyWrite specifies whether an HTTP Request Body can be modified.
	// It defaults to false, meaning any operation on OnRequestBody will be ignored.
	// When enabled, operations on OnRequestBody, including modifications to the HTTP Request body, are permitted.
	//
	// Warning! Use this option only when necessary, as enabling it is equivalent to granting access
	// to potentially sensitive information that shouldn't be visible to the middleware otherwise.
	EnableRequestBodyWrite bool

	// EnableResponseBodyRead specifies whether an HTTP Response Body can be accessed or not.
	// It defaults to false, meaning any operation on OnResponseBody will be ignored.
	// When enabled, operations on OnResponseBody are allowed,
	// but attempts to modify the HTTP Response body will result in a panic, which returns with 502 (Bad Gateway).
	//
	// Warning! Use this option only when necessary, as enabling it is equivalent to granting access
	// to potentially sensitive information that shouldn't be visible to the middleware otherwise.
	EnableResponseBodyRead bool

	// EnableResponseBodyWrite specifies whether an HTTP Response Body can be accessed or not
	// It defaults to false, meaning any operation on OnResponseBody will be ignored.
	// When enabled, operations on OnResponseBody, including modifications to the HTTP Response body, are permitted.
	//
	// Warning! Use this option only when necessary, as enabling it is equivalent to granting access
	// to potentially sensitive information that shouldn't be visible to the middleware otherwise.
	EnableResponseBodyWrite bool

	// DisableChunkedEncodingRequest specifies whether the request body should not be chunked during OnRequestBody phases.
	// This setting applies when EnableRequestBodyWrite is enabled.
	// It defaults to false, meaning if EnableRequestBodyWrite is enabled, the filter is expected to modify the request body, hence it will be chunked following the Content-Length header removal.
	// However, this setting only relevant for protocols prior to HTTP/2, as it will be treated as having chunked encoding (Transfer-Encoding: chunked).
	// Therefore turning this on will preserve the Content-Length header.
	//
	// Note that when this setting is turned on (re: disabled), the request headers will be buffered into the filter manager.
	// Hence, you can modify request headers as well in the OnRequestBody phase.
	DisableChunkedEncodingRequest bool

	// DisableChunkedEncodingResponse specifies whether the response should not be chunked during OnResponseBody phases.
	// This setting applies when EnableResponseBodyWrite is enabled.
	// It defaults to false, meaning if EnableResponseBodyWrite is enabled,
	// the filter is expected to modify the response body, hence it will be chunked following the Content-Length header removal.
	// However, this setting only relevant for protocols prior to HTTP/2, as it will be treated as having chunked encoding (Transfer-Encoding: chunked).
	// Therefore turning this on will preserve the Content-Length header.
	//
	DisableChunkedEncodingResponse bool
}

ConfigOptions represents the configuration options for the filters.

type Context

type Context interface {
	RuntimeContext

	HttpFilterContext

	// StatusType is a low-level API used to specify the type of status to be communicated to Envoy.
	//
	// Returns the status type.
	StatusType() api.StatusType

	// Committed indicates whether the current context has already completed its processing
	// within the filter and forwarded the result to Envoy.
	//
	// Returns true if the context has already committed, false otherwise.
	Committed() bool
}

Context represents the interface for a context within the filter. It extends the RuntimeContext and HttpFilterContext interfaces.

func NewContext added in v0.3.1

func NewContext(cb api.FilterCallbacks, o contextOptions) (Context, error)

NewContext creates a new context object for the filter.

type ErrorHandler

type ErrorHandler func(Context, error) api.StatusType

ErrorHandler is a function type that handles errors in the HTTP filter.

type Header interface {
	api.HeaderMap

	// Export returns a copy of the headers as an http.Header form.
	// This implies that any changes made to the copy of headers will not affect the original headers.
	// If there's a need to alter the headers, you can do so directly via this interface, or
	// you can use the Export method in conjunction with the Import method to affect the original headers.
	//
	Export() http.Header

	// Import overwrites the original headers with the given headers.
	// Please use this method with caution, and it's advisable to use it in conjunction with the return of Export method as the headers' source.
	//
	Import(headers http.Header)
}

Header represents an HTTP header. It extends the api.HeaderMap interface and provides additional methods for working with headers.

type HttpFilter

type HttpFilter interface {
	// OnBegin is executed during filter startup.
	//
	// The OnBegin method is called when the filter is initialized.
	// It can be used by the user to perform filter preparation tasks, such as:
	// - Retrieving filter configuration (if provided)
	// - Registering filter handlers
	// - Capturing user-generated metrics
	//
	// If an error is returned, the filter will be ignored.
	OnBegin(c RuntimeContext, ctrl HttpFilterController) error

	// OnComplete is executed when the filter is completed.
	//
	// The OnComplete method is called when the filter is about to be destroyed.
	// It can be used by the user to perform filter completion tasks, such as:
	// - Capturing user-generated metrics
	// - Cleaning up resources
	//
	// If an error is returned, nothing happens.
	OnComplete(c Context) error
}

HttpFilter defines an interface for an HTTP filter used in Envoy. It provides methods for managing filter names, startup, and completion. This interface is specifically designed as a mechanism for onboarding the user HTTP filters to Envoy. HttpFilter is always renewed for every request.

type HttpFilterAction

type HttpFilterAction uint

HttpFilterAction represents the action to be taken on each phase of an HTTP filter.

const (
	// ActionSkip is basically a no-op action, which mean the filter phase will be skipped.
	// From Envoy perspective, this is equivalent to a Continue status.
	ActionSkip HttpFilterAction = iota

	// ActionContinue is operation action that continues the current filter phase.
	// From Envoy perspective, this is equivalent to a Continue status.
	// Although the status is identical to ActionSkip, the purpose of ActionContinue
	// is to indicate that the current phase is operating correctly and needs to advance to the subsequent filter phase.
	ActionContinue

	// ActionPause is an operation action that pause the current filter phase, preventing it from being sent to downstream or upstream.
	// This pause could be essential as subsequent filter phases might depend on the previous phases.
	// For instance, the EncodeData phase might need modifications to the headers, which are managed in the EncodeHeaders phase.
	// Hence, EncodeHeaders should return with ActionPause, allowing for potential header changes in the EncodeData phase.
	// Note that when using this action, the subsequent filter phase must return with ActionContinue; otherwise the filter chain might hang.
	//
	// From the perspective of Envoy, this is similar to a StopAndBuffer status.
	ActionPause

	// ActionWait is an operation action that waits the current filter phase.
	// This is particularly relevant during data streaming phases like DecodeData or EncodeData,
	// where the filter phase needs to wait until the complete body is buffered on the Envoy host side.
	//
	// From Envoy's perspective, this is equivalent to a StopNoBuffer status.
	ActionWait
)

type HttpFilterCompletionFunc

type HttpFilterCompletionFunc func()

HttpFilterCompletionFunc represents a function type for completing an HTTP filter.

type HttpFilterContext

type HttpFilterContext interface {
	// RequestHeader provides an interface to access and modify HTTP Request header, including
	// add, overwrite, or delete existing header.
	//
	// A panic is returned when the filter has not yet traversed the HTTP request or OnRequestHeader phase is disabled.
	// Please refer to the previous Envoy's HTTP filter behavior.
	//
	RequestHeader() Header

	// ResponseHeader provides an interface to access and modify HTTP Response header, including
	// add, overwrite, or delete existing header.
	//
	// A panic is returned when OnResponseHeader phase is disabled or ResponseHeader accessed outside from the following phases:
	// OnResponseHeader, OnResponseBody
	//
	ResponseHeader() Header

	// RequestBodyBuffer provides an interface to access and manipulate an HTTP Request body.
	//
	// A panic is returned when OnRequestBody phase is disabled or RequestBody accessed outside from the following phases:
	// OnRequestBody, OnResponseHeader, OnResponseBody
	//
	RequestBody() Body

	// ResponseBody provides an interface access and manipulate an HTTP Response body.
	//
	// A panic is returned when OnResponseBody phase is disabled or ResponseBody accessed outside from the following phases:
	// OnResponseBody
	//
	ResponseBody() Body

	// Request returns an http.Request struct, which is a read-only data.
	// Any attempts to alter this value will not affect to the actual request.
	// For any modifications, please use RequestHeader or RequestBody.
	//
	// Note: The request body only available during the OnRequestBody phase.
	//
	// A panic is returned if the filter has not yet traversed the HTTP request or the Request body access setting is turned off.
	// Please see to the previous Envoy's HTTP filter behavior.
	//
	Request() *http.Request

	// Response returns an http.Response struct, which is a read-only data.
	// Any attempts to alter this value will not affect to the actual response.
	// For any modifications, please use ResponseHeader or ResponseBody.
	//
	// Note: The response body only available during the OnResponseBody phase.
	//
	// A panic is returned if the Response body access setting is turned off or if Response is accessed outside of the following phases:
	// OnResponseHeader, or OnResponseBody
	//
	Response() *http.Response

	// SetRequestHost modifies the host of the request.
	// This can be used to dynamically change the request host based on specific conditions for routing.
	// However, to re-evaluate routing decisions, the filter must explicitly trigger ReloadRoute,
	// or the AutoReloadRouteOnHeaderChange option must be enabled in the ConfigOptions.
	//
	SetRequestHost(host string)

	// SetRequestMethod modifies the method of the request (GET, POST, etc.).
	// This can be used to dynamically change the request host based on specific conditions for routing.
	// However, to re-evaluate routing decisions, the filter must explicitly trigger ReloadRoute,
	// or the AutoReloadRouteOnHeaderChange option must be enabled in the ConfigOptions.
	//
	SetRequestMethod(method string)

	// SetRequestPath modifies the path of the request.
	// This can be used to dynamically change the request host based on specific conditions for routing.
	// However, to re-evaluate routing decisions, the filter must explicitly trigger ReloadRoute,
	// or the AutoReloadRouteOnHeaderChange option must be enabled in the ConfigOptions.
	//
	SetRequestPath(path string)

	// LoadRequestHeaders is a low-level API, it loads HTTP request headers from Envoy during DecodeHeaders phase
	//
	LoadRequestHeaders(api.RequestHeaderMap)

	// LoadResponseHeaders is a low-level API, it loads HTTP response headers from Envoy during EncodeHeaders phase
	//
	LoadResponseHeaders(api.ResponseHeaderMap)

	// LoadRequestBody is a low-level API, it loads HTTP request body from Envoy during DecodeData phase
	//
	LoadRequestBody(buffer api.BufferInstance, endStream bool)

	// LoadResponseBody is a low-level API, it loads HTTP response body from Envoy during EncodeData phase
	//
	LoadResponseBody(buffer api.BufferInstance, endStream bool)

	// IsRequestBodyAccessible checks if the request body is accessible for reading or writing.
	//
	IsRequestBodyAccessible() bool

	// IsRequestBodyReadable specifies whether an HTTP Request body is readable or not.
	//
	IsRequestBodyReadable() bool

	// IsRequestBodyWritable specifies whether an HTTP Request body is writeable or not.
	//
	IsRequestBodyWritable() bool

	// IsResponseBodyAccessible checks if the response body is accessible for reading or writing.
	//
	IsResponseBodyAccessible() bool

	// IsResponseBodyReadable specifies whether an HTTP Response body is readable or not.
	//
	IsResponseBodyReadable() bool

	// IsResponseBodyWritable specifies whether an HTTP Response body is writeable or not.
	//
	IsResponseBodyWritable() bool

	// SendResponse dispatches a response with a specified status code, body, and optional localreply options.
	// Use the JSON() method when you need to respond with a JSON content-type.
	// For plain text responses, use the String() method.
	// Use SendResponse only when you need to send a response with a custom content type.
	//
	// This action halts the handler chaining and immediately returns back to Envoy.
	SendResponse(code int, bodyText string, opts ...LocalReplyOption) error

	// JSON dispatches a JSON response with a status code.
	//
	// This action halts the handler chaining and immediately returns back to Envoy.
	JSON(code int, b []byte, opts ...LocalReplyOption) error

	// String dispatches a plain text response with a status code.
	//
	// This action halts the handler chaining and immediately returns back to Envoy.
	String(code int, s string, opts ...LocalReplyOption) error

	// SkipNextPhase immediately returns to the Envoy without further progressing to the next handler.
	// This action also enables users to bypass the next phase.
	// In HTTP request flows, invoking it from OnRequestHeader skips OnRequestBody phase.
	// In HTTP response flows, invoking it from OnResponseHeader skips OnResponseBody phase.
	//
	SkipNextPhase() error

	// ReloadRoute reloads the route configuration, which basically re-evaluates the routing decisions.
	// You can enable this feature by setting the `RouteReloadable` field in the ConfigOptions.
	// Example use cases:
	// - When user wants to modify headers based on certain conditions, then later decides whether the request should be routed to a different cluster or upstream.
	// - When user wants to modify the routing decision based on the request body.
	//
	ReloadRoute()
}

HttpFilterContext represents the context object for an HTTP filter. It provides methods to access and modify various aspects of the HTTP request and response.

type HttpFilterController

type HttpFilterController interface {
	// SetErrorHandler sets a custom error handler for an HTTP Filter.
	// The error handler will be called when an error occurs during the execution of the HTTP filter.
	//
	SetErrorHandler(handler ErrorHandler)

	// AddHandler adds an HTTP Filter Handler to the controller,
	// which should be run during filter startup (HttpFilter.OnBegin).
	// It's important to note the order when adding filter handlers.
	// While HTTP requests follow FIFO sequences, HTTP responses follow LIFO sequences.
	//
	// Example usage:
	//
	//	func (f *UserFilter) OnBegin(c RuntimeContext, ctrl HttpFilterController) error {
	//		...
	//		ctrl.AddHandler(handlerA)
	//		ctrl.AddHandler(handlerB)
	//		ctrl.AddHandler(handlerC)
	//		ctrl.AddHandler(handlerD)
	//	}
	//
	// During HTTP requests, traffic flows from `handlerA -> handlerB -> handlerC -> handlerD`.
	// During HTTP responses, traffic flows in reverse: `handlerD -> handlerC -> handlerB -> handlerA`.
	//
	AddHandler(handler HttpFilterHandler)
}

HttpFilterController represents a controller for managing HTTP filters.

type HttpFilterDecodeProcessor

type HttpFilterDecodeProcessor interface {
	// HandleOnRequestHeader manages operations during the OnRequestHeader phase.
	HandleOnRequestHeader(Context) error

	// HandleOnRequestBody manages operations during the OnRequestBody phase.
	HandleOnRequestBody(Context) error
}

HttpFilterDecodeProcessor is an interface that defines the methods for processing HTTP filter decode phases.

type HttpFilterDecoderFunc

type HttpFilterDecoderFunc func(Context, HttpFilterDecodeProcessor) (HttpFilterAction, error)

HttpFilterDecoderFunc is a function type that represents a decoder for HTTP filters. It is used during the decoder phases, which is when the filter processes the incoming request.

type HttpFilterEncodeProcessor

type HttpFilterEncodeProcessor interface {
	// HandleOnResponseHeader manages operations during the OnResponseHeader phase.
	HandleOnResponseHeader(Context) error

	// HandleOnResponseBody manages operations during the OnResponseBody phase.
	HandleOnResponseBody(Context) error
}

HttpFilterEncodeProcessor is an interface that defines the methods for processing HTTP filter encode phases.

type HttpFilterEncoderFunc

type HttpFilterEncoderFunc func(Context, HttpFilterEncodeProcessor) (HttpFilterAction, error)

HttpFilterEncoderFunc is a function type that represents an encoder for HTTP filters. It is used during the encoder phases, which is when the filter processes the upstream response.

type HttpFilterFactory added in v0.4.0

type HttpFilterFactory func() HttpFilter

HttpFilterFactory defines a factory func for creating an HttpFilter.

It is passed to RunHttpFilter & buildHttpFilterManager and called in buildHttpFilterManager to create a new HTTP filter on each request.

It should be defined within the init() func of the HTTP filter and must return a struct that satisfies HttpFilter. It may also be used to inject dependencies into this struct, if required by the handler.

type HttpFilterHandler

type HttpFilterHandler interface {
	// Disable disables the HTTP filter handler.
	//
	// It returns a boolean value indicating whether the HTTP filter handler is disabled.
	Disable() bool

	// OnRequestHeader is called when processing the HTTP request header during the OnRequestBody phase.
	//
	OnRequestHeader(c Context) error

	// OnRequestBody is called when processing the HTTP request body during the OnRequestBody phase.
	//
	OnRequestBody(c Context) error

	// OnResponseHeader is called when processing the HTTP response header during the OnResponseHeader phase.
	//
	OnResponseHeader(c Context) error

	// OnResponseBody is called when processing the HTTP response body during the OnResponseBody phase.
	//
	OnResponseBody(c Context) error
}

HttpFilterHandler represents an interface for an HTTP filter handler. In a typical HTTP flow, the sequence of events can be as follows: OnRequestHeader -> OnRequestBody -> <Any number of intermediate Envoy processes> -> OnResponseHeader -> OnResponseBody HttpFilterHandler is an interface that defines the methods to handle HTTP filter operations.

type HttpFilterProcessor

type HttpFilterProcessor interface {
	HttpFilterDecodeProcessor
	HttpFilterEncodeProcessor

	// SetNext sets the next HttpFilterProcessor in the sequence.
	SetNext(HttpFilterProcessor)

	// SetPrevious sets the previous HttpFilterProcessor in the sequence.
	SetPrevious(HttpFilterProcessor)
}

HttpFilterProcessor is an interface that defines the methods for processing HTTP filter phases and enabling chaining between user's HTTP filter handlers.

type HttpFilterResult

type HttpFilterResult struct {
	// Action represents the action to be taken based on the filter result.
	Action HttpFilterAction
	// Err represents the error encountered during the filter operation, if any.
	Err error
	// Status represents the final status of the filter processing.
	Status api.StatusType
}

HttpFilterResult represents the result of an HTTP filter operation.

func (*HttpFilterResult) Finalize

func (res *HttpFilterResult) Finalize(c Context, errorHandler ErrorHandler)

Finalize performs the finalization logic for the HttpFilterResult. It recovers from any panics, sets the appropriate error and status, and determines the action to be taken based on the result.

type HttpFilterServer

type HttpFilterServer interface {
	// ServeDecodeFilter serves decode phase of an HTTP filter.
	// This method is designed for internal use as it is used during the decoding phase only.
	// Decode phase is when the filter processes the incoming request, which consist of processing headers and body.
	//
	ServeDecodeFilter(HttpFilterDecoderFunc) *HttpFilterResult

	// ServeEncodeFilter serves encode phase of an HTTP filter.
	// This method is designed for internal use as it is used during the encoding phase only.
	// Encode phase is when the filter processes the upstream response, which consist of processing headers and body.
	//
	ServeEncodeFilter(HttpFilterEncoderFunc) *HttpFilterResult

	// Complete is called when the HTTP filter server has processed the request and issued a response.
	//
	Complete()
}

HttpFilterServer is an HTTP filter server used for handling HTTP requests and responses. It provides methods to serve decode and encode filters, as well as to finalize the processing of the HTTP filter server.

type LocalReplyOption added in v0.4.0

type LocalReplyOption func(o *LocalReplyOptions)

func LocalReplyWithGRPCStatus added in v0.4.0

func LocalReplyWithGRPCStatus(status int64) LocalReplyOption

LocalReplyWithGRPCStatus sets the gRPC status code for the local reply options. The status code is used to indicate the result of the gRPC operation.

func LocalReplyWithHTTPHeaders added in v0.4.0

func LocalReplyWithHTTPHeaders(headers http.Header) LocalReplyOption

LocalReplyWithHTTPHeaders sets the HTTP headers for the local reply options.

func LocalReplyWithRCDetails added in v0.4.0

func LocalReplyWithRCDetails(detail string) LocalReplyOption

LocalReplyWithRCDetails sets response code details for a request/response to the envoy context It accepts a string, but commonly for convention purpose please check ResponseCodeDetailPrefix.

func LocalReplyWithStatusType added in v0.4.0

func LocalReplyWithStatusType(status api.StatusType) LocalReplyOption

LocalReplyWithStatusType sets the status type for the local reply options.

type LocalReplyOptions added in v0.4.0

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

func NewLocalReplyOptions added in v0.4.0

func NewLocalReplyOptions(opts ...LocalReplyOption) *LocalReplyOptions

type Metrics

type Metrics interface {
	// Gauge sets gauge statistics that can record both increasing and decreasing metrics. E.g., current active requests.
	Gauge(name string, labelKeyValues ...string) api.GaugeMetric

	// Counter sets counter statistics that only record for increase, but never decrease metrics. E.g., total requests.
	Counter(name string, labelKeyValues ...string) api.CounterMetric

	// Histogram is still a WIP
	Histogram(name string, labelKeyValues ...string) api.HistogramMetric
}

Metrics is an interface for defining various types of metrics. At presents, it only supports Gauge and Counter.

type PassthroughHttpFilterHandler

type PassthroughHttpFilterHandler struct{}

func (PassthroughHttpFilterHandler) Disable

func (PassthroughHttpFilterHandler) OnRequestBody

func (PassthroughHttpFilterHandler) OnRequestBody(c Context) error

func (PassthroughHttpFilterHandler) OnRequestHeader

func (PassthroughHttpFilterHandler) OnRequestHeader(c Context) error

func (PassthroughHttpFilterHandler) OnResponseBody

func (PassthroughHttpFilterHandler) OnResponseBody(c Context) error

func (PassthroughHttpFilterHandler) OnResponseHeader

func (PassthroughHttpFilterHandler) OnResponseHeader(c Context) error

type ResponseCodeDetailPrefix

type ResponseCodeDetailPrefix string

ResponseCodeDetailPrefix represents a prefix for response code details.

func (ResponseCodeDetailPrefix) Wrap

func (prefix ResponseCodeDetailPrefix) Wrap(message string) string

Wrap wraps message with given response code detail prefix

type RuntimeContext

type RuntimeContext interface {
	// GetProperty is a helper function to fetch Envoy attributes based on https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/attributes.
	// Currently, it only supports value that has a string-like format, work in progress for List/Map format.
	//
	GetProperty(name, defaultVal string) (string, error)

	// StreamInfo offers an interface for retrieving comprehensive details about the incoming HTTP traffic, including
	// information such as the route name, filter chain name, dynamic metadata, and more.
	// It provides direct access to low-level Envoy information, so it's important to use it with a clear understanding of your intent.
	//
	StreamInfo() api.StreamInfo

	// GetFilterConfig returns the filter configuration associated with the route.
	// It defaults to the parent filter configuration if no route filter configuration was found.
	// Otherwise, once typed_per_filter_config present in the route then it will return the child filter configuration.
	// Whether these filter configurations can be merged depends on the filter configuration struct tags.
	//
	GetFilterConfig() interface{}

	// GetCache returns a Cache.
	// Use this Cache when variable initialization is expensive or requires a statefulness.
	//
	GetCache() Cache

	// Log provides a logger from the plugin to the Envoy Log. It accessible under Envoy `http` and/or `golang` component.
	// Additionally, only debug, info, and error log levels are being taken into account.
	// e.g., Envoy flag `--component-log-level http:{debug,info,warn,error,critical},golang:{debug,info,warn,error,critical}`
	//
	Log() logr.Logger

	// Metrics provides an interface for user to create their custom metrics.
	//
	Metrics() Metrics
}

RuntimeContext represents the runtime context for the filter in Envoy. It provides various methods to interact with the Envoy proxy and retrieve information about the HTTP traffic.

Directories

Path Synopsis
pkg
test

Jump to

Keyboard shortcuts

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