zanzibar

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2018 License: MIT Imports: 37 Imported by: 778

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnsureEmpty

func EnsureEmpty(r io.Reader, stage string) error

EnsureEmpty ensures that the specified reader is empty. If the reader is not empty, it returns an error with the specified stage in the message.

func GetBuffer

func GetBuffer() *bytes.Buffer

GetBuffer returns a new Byte Buffer from the buffer pool that has been reset

func GetDirnameFromRuntimeCaller

func GetDirnameFromRuntimeCaller(file string) string

GetDirnameFromRuntimeCaller will compute the current dirname if passed a filename from runtime.Caller(0). This is useful for doing __dirname/__FILE__ for golang.

func GetHostname

func GetHostname() string

GetHostname returns hostname

func GetRequestEndpointFromCtx

func GetRequestEndpointFromCtx(ctx context.Context) string

GetRequestEndpointFromCtx returns the endpoint, if it exists on context

func GetRequestUUIDFromCtx

func GetRequestUUIDFromCtx(ctx context.Context) uuid.UUID

GetRequestUUIDFromCtx returns the RequestUUID, if it exists on context TODO: in future, we can extend this to have request object

func GetRoutingDelegateFromCtx

func GetRoutingDelegateFromCtx(ctx context.Context) string

GetRoutingDelegateFromCtx returns the tchannel routing delegate info extracted from context.

func LogErrorWarnTimeout

func LogErrorWarnTimeout(logger *zap.Logger, err error, msg string)

LogErrorWarnTimeout logs warnings for timeout errors, otherwise logs errors TODO: We want to improve the classification of errors, similar to: https://github.com/uber/tchannel-node/blob/master/errors.js#L907-L930

func NewInstrumentedZapCore

func NewInstrumentedZapCore(
	core zapcore.Core,
	allHostsScope tally.Scope,
) zapcore.Core

NewInstrumentedZapCore will return a zapcore.Core that emits "logged" metrics, one counter for each level.

func NewTChannelLogger

func NewTChannelLogger(logger *zap.Logger) tchannel.Logger

NewTChannelLogger creates a TChannel logger given a zap logger

func NewTChannelStatsReporter

func NewTChannelStatsReporter(scope tally.Scope) tchannel.StatsReporter

NewTChannelStatsReporter returns a StatsReporter using the given tally.Scope.

func PutBuffer

func PutBuffer(buf *bytes.Buffer)

PutBuffer returns byte buffer to the buffer pool

func ReadHeaders

func ReadHeaders(r io.Reader) (map[string]string, error)

ReadHeaders reads key-value pairs encoded using WriteHeaders.

func ReadStruct

func ReadStruct(reader io.Reader, s RWTStruct) error

ReadStruct reads the given Thriftrw struct.

func WithEndpointField

func WithEndpointField(ctx context.Context, endpoint string) context.Context

WithEndpointField adds the endpoint information in the request context.

func WithRoutingDelegate

func WithRoutingDelegate(ctx context.Context, rd string) context.Context

WithRoutingDelegate adds the tchannel routing delegate information in the request context.

func WriteHeaders

func WriteHeaders(w io.Writer, headers map[string]string) error

WriteHeaders writes the given key-value pairs using the following encoding: len~2 (k~4 v~4)~len

Types

type ClientHTTPRequest

type ClientHTTPRequest struct {
	ClientID   string
	MethodName string

	Logger *zap.Logger
	// contains filtered or unexported fields
}

ClientHTTPRequest is the struct for making client requests using an outbound http client.

func NewClientHTTPRequest

func NewClientHTTPRequest(
	clientID, methodName string,
	client *HTTPClient,
) *ClientHTTPRequest

NewClientHTTPRequest allocates a ClientHTTPRequest

func (*ClientHTTPRequest) CheckHeaders

func (req *ClientHTTPRequest) CheckHeaders(expected []string) error

CheckHeaders verifies that the outbound request contains required headers

func (*ClientHTTPRequest) Do

Do will send the request out.

func (*ClientHTTPRequest) InjectSpanToHeader

func (req *ClientHTTPRequest) InjectSpanToHeader(span opentracing.Span, format interface{}) error

InjectSpanToHeader will inject span to request header This method is current used for unit tests TODO: we need to set source and test code as same pkg name which would makes UTs easier

func (*ClientHTTPRequest) WriteJSON

func (req *ClientHTTPRequest) WriteJSON(
	method, url string,
	headers map[string]string,
	body json.Marshaler,
) error

WriteJSON will send a json http request out.

type ClientHTTPResponse

type ClientHTTPResponse struct {
	StatusCode int
	Header     http.Header
	// contains filtered or unexported fields
}

ClientHTTPResponse is the struct managing the client response when making outbound http calls.

func NewClientHTTPResponse

func NewClientHTTPResponse(
	req *ClientHTTPRequest,
) *ClientHTTPResponse

NewClientHTTPResponse allocates a client http response object to track http response.

func (*ClientHTTPResponse) CheckOKResponse

func (res *ClientHTTPResponse) CheckOKResponse(okResponses []int)

CheckOKResponse checks if the status code is OK.

func (*ClientHTTPResponse) GetRawBody

func (res *ClientHTTPResponse) GetRawBody() []byte

GetRawBody returns the body as byte array if it has been read.

func (*ClientHTTPResponse) ReadAll

func (res *ClientHTTPResponse) ReadAll() ([]byte, error)

ReadAll reads bytes from response.

func (*ClientHTTPResponse) ReadAndUnmarshalBody

func (res *ClientHTTPResponse) ReadAndUnmarshalBody(v interface{}) error

ReadAndUnmarshalBody will try to unmarshal non pointer value or fail

type ConfigOption

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

ConfigOption points to a collection of bytes representing a file. This is either the full contents of the file as bytes, or a string poiting to a file

func ConfigFileContents

func ConfigFileContents(fileBytes []byte) *ConfigOption

ConfigFileContents creates a ConfigFile representing the contents of the file

func ConfigFilePath

func ConfigFilePath(path string) *ConfigOption

ConfigFilePath creates a ConfigFile represented as a path

type DefaultDependencies

type DefaultDependencies struct {
	Logger  *zap.Logger
	Scope   tally.Scope
	Tracer  opentracing.Tracer
	Config  *StaticConfig
	Channel *tchannel.Channel
}

DefaultDependencies type

type Gateway

type Gateway struct {
	HTTPPort         int32
	TChannelPort     int32
	RealHTTPPort     int32
	RealHTTPAddr     string
	RealTChannelPort int32
	RealTChannelAddr string
	WaitGroup        *sync.WaitGroup
	Channel          *tchannel.Channel
	Logger           *zap.Logger
	RootScope        tally.Scope
	AllHostScope     tally.Scope
	PerHostScope     tally.Scope
	ServiceName      string
	Config           *StaticConfig
	HTTPRouter       *HTTPRouter
	TChannelRouter   *TChannelRouter
	Tracer           opentracing.Tracer
	// contains filtered or unexported fields
}

Gateway type

func CreateGateway

func CreateGateway(
	config *StaticConfig, opts *Options,
) (*Gateway, error)

CreateGateway func

func (*Gateway) Bootstrap

func (gateway *Gateway) Bootstrap() error

Bootstrap func

func (*Gateway) Close

func (gateway *Gateway) Close()

Close shuts down the servers and returns immediately

func (*Gateway) InspectOrDie

func (gateway *Gateway) InspectOrDie() map[string]interface{}

InspectOrDie inspects the config for this gateway

func (*Gateway) Shutdown

func (gateway *Gateway) Shutdown()

Shutdown starts the graceful shutdown, blocks until it is complete

func (*Gateway) ShutdownTimeout

func (gateway *Gateway) ShutdownTimeout() time.Duration

ShutdownTimeout returns the shutdown configured timeout, which default to 10s.

func (*Gateway) SubLogger

func (gateway *Gateway) SubLogger(name string, level zapcore.Level) *zap.Logger

SubLogger returns a sub logger clone with given name and log level.

func (*Gateway) Wait

func (gateway *Gateway) Wait()

Wait for gateway to close the server

type HTTPClient

type HTTPClient struct {
	Client         *http.Client
	BaseURL        string
	DefaultHeaders map[string]string
	// contains filtered or unexported fields
}

HTTPClient defines a http client.

func NewHTTPClient

func NewHTTPClient(
	logger *zap.Logger,
	scope tally.Scope,
	clientID string,
	methodNames []string,
	baseURL string,
	defaultHeaders map[string]string,
	timeout time.Duration,
) *HTTPClient

NewHTTPClient will allocate a http client.

type HTTPRouter

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

HTTPRouter data structure to handle and register endpoints

func NewHTTPRouter

func NewHTTPRouter(gateway *Gateway) *HTTPRouter

NewHTTPRouter allocates a HTTP router

func (*HTTPRouter) Register

func (router *HTTPRouter) Register(
	method, urlpattern string,
	endpoint *RouterEndpoint,
) error

Register will register an endpoint with the router.

func (*HTTPRouter) RegisterRaw

func (router *HTTPRouter) RegisterRaw(
	method, prefix string,
	handler http.HandlerFunc,
)

RegisterRaw register a raw handler function. Such a function take raw http req/writer. Use this only to integrated third-party, like pprof debug handlers

func (*HTTPRouter) ServeHTTP

func (router *HTTPRouter) ServeHTTP(w http.ResponseWriter, r *http.Request)

type HTTPServer

type HTTPServer struct {
	*http.Server
	Logger *zap.Logger

	RealPort int32
	RealIP   string
	RealAddr string
	// contains filtered or unexported fields
}

HTTPServer like, http.Server but improved management of listening and serving Allows you to listen on port 0, query for real OS port and then serve requests

func (*HTTPServer) Close

func (server *HTTPServer) Close()

Close the listening socket

func (*HTTPServer) JustListen

func (server *HTTPServer) JustListen() (net.Listener, error)

JustListen will only listen on port and query real addr

func (*HTTPServer) JustServe

func (server *HTTPServer) JustServe(waitGroup *sync.WaitGroup)

JustServe will serve all incoming requests

type HTTPStatusMap

type HTTPStatusMap map[int]tally.Counter

HTTPStatusMap is statusCode -> according counter map

func (HTTPStatusMap) IncrStatus

func (hsm HTTPStatusMap) IncrStatus(statusCode int, count int64)

IncrStatus will increase according status code counter

type HandlerFn

type HandlerFn func(
	context.Context,
	*ServerHTTPRequest,
	*ServerHTTPResponse,
)

HandlerFn is a func that handles ServerHTTPRequest

type Header interface {
	Get(key string) (string, bool)
	Add(key string, value string)
	Set(key string, value string)
	Keys() []string
	Ensure(keys []string, logger *zap.Logger) error
}

Header defines methods on ServerHeaders

type InboundHTTPMetrics

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

InboundHTTPMetrics ...

func NewInboundHTTPMetrics

func NewInboundHTTPMetrics(scope tally.Scope) *InboundHTTPMetrics

NewInboundHTTPMetrics returns inbound HTTP metrics

type InboundTChannelMetrics

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

InboundTChannelMetrics ...

func NewInboundTChannelMetrics

func NewInboundTChannelMetrics(scope tally.Scope) *InboundTChannelMetrics

NewInboundTChannelMetrics returns inbound TChannel metrics

type MiddlewareHandle

type MiddlewareHandle interface {
	// implement HandleRequest for your middleware. Return false
	// if the handler writes to the response body.
	HandleRequest(
		ctx context.Context,
		req *ServerHTTPRequest,
		res *ServerHTTPResponse,
		shared SharedState,
	) bool
	// implement HandleResponse for your middleware. Return false
	// if the handler writes to the response body.
	HandleResponse(
		ctx context.Context,
		res *ServerHTTPResponse,
		shared SharedState,
	)
	// return any shared state for this middleware.
	JSONSchema() *jsonschema.Document
	Name() string
}

MiddlewareHandle used to define middleware

type MiddlewareStack

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

MiddlewareStack is a stack of Middleware Handlers that can be invoked as an Handler. MiddlewareStack middlewares are evaluated for requests in the order that they are added to the stack followed by the underlying HandlerFn. The middleware responses are then executed in reverse.

func NewStack

func NewStack(middlewares []MiddlewareHandle,
	handle HandlerFn) *MiddlewareStack

NewStack returns a new MiddlewareStack instance with no middleware preconfigured.

func (*MiddlewareStack) Handle

Handle executes the middlewares in a stack and underlying handler.

func (*MiddlewareStack) Middlewares

func (m *MiddlewareStack) Middlewares() []MiddlewareHandle

Middlewares returns a list of all the handlers in the current MiddlewareStack.

type MiddlewareTchannelHandle

type MiddlewareTchannelHandle interface {
	// implement HandleRequest for your middleware. Return false
	// if the handler writes to the response body.
	HandleRequest(
		ctx context.Context,
		reqHeaders map[string]string,
		wireValue *wire.Value,
		shared TchannelSharedState) (bool, error)

	// implement HandleResponse for your middleware. Return false
	// if the handler writes to the response body.
	HandleResponse(
		ctx context.Context,
		rwt RWTStruct,
		shared TchannelSharedState) RWTStruct

	// return any shared state for this middleware.
	JSONSchema() *jsonschema.Document
	Name() string
}

MiddlewareTchannelHandle used to define middleware

type MiddlewareTchannelStack

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

MiddlewareTchannelStack is a stack of Middleware Handlers that can be invoked as an Handler. MiddlewareTchannelStack middlewares are evaluated for requests in the order that they are added to the stack followed by the underlying HandlerFn. The middleware responses are then executed in reverse.

func NewTchannelStack

func NewTchannelStack(middlewares []MiddlewareTchannelHandle,
	handler TChannelHandler) *MiddlewareTchannelStack

NewTchannelStack returns a new MiddlewareStack instance with no middleware preconfigured.

func (*MiddlewareTchannelStack) Handle

func (m *MiddlewareTchannelStack) Handle(
	ctx context.Context,
	reqHeaders map[string]string,
	wireValue *wire.Value) (bool, RWTStruct, map[string]string, error)

Handle executes the middlewares in a stack and underlying handler.

func (*MiddlewareTchannelStack) TchannelMiddlewares

func (m *MiddlewareTchannelStack) TchannelMiddlewares() []MiddlewareTchannelHandle

TchannelMiddlewares returns a list of all the handlers in the current MiddlewareStack.

type Options

type Options struct {
	MetricsBackend tally.CachedStatsReporter
	LogWriter      zapcore.WriteSyncer
}

Options configures the gateway

type OutboundHTTPMetrics

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

OutboundHTTPMetrics ...

func NewOutboundHTTPMetrics

func NewOutboundHTTPMetrics(scope tally.Scope) *OutboundHTTPMetrics

NewOutboundHTTPMetrics returns outbound HTTP metrics

type OutboundTChannelMetrics

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

OutboundTChannelMetrics ...

func NewOutboundTChannelMetrics

func NewOutboundTChannelMetrics(scope tally.Scope) *OutboundTChannelMetrics

NewOutboundTChannelMetrics returns outbound TChannel metrics

type PostResponseCB

type PostResponseCB func(ctx context.Context, method string, response RWTStruct)

PostResponseCB registers a callback that is run after a response has been completely processed (e.g. written to the channel). This gives the server a chance to clean up resources from the response object

type RWTStruct

type RWTStruct interface {
	ToWire() (wire.Value, error)
	FromWire(wire.Value) error
}

RWTStruct abstracts the request/response structs generated by thriftrw.

type RawTChannelClient

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

RawTChannelClient is like TChannel client, but without ClientID or MethodNames. Its Logs and metrics are not scoped per method, and not used for generate TChannel clients. It is intended to be used internally to communicate with a test service, and the way to that is via `MakeTChannelRequest` method defined on the test service. The TChannel client is not exposed, so the MethodNames are less relevant. The only downside is that, without the map, the client logs does not have the method information (because there isn't a method anyway), but the Thrift service and method information is still there.

func NewRawTChannelClient

func NewRawTChannelClient(
	ch *tchannel.Channel,
	logger *zap.Logger,
	scope tally.Scope,
	opt *TChannelClientOption,
) *RawTChannelClient

NewRawTChannelClient returns a RawTChannelClient that makes calls over the given tchannel to the given thrift service. There is no guarantee that the given thrift service and method is valid for given Channel. It is intended to be used internally for testing.

func (*RawTChannelClient) Call

func (r *RawTChannelClient) Call(
	ctx context.Context,
	thriftService, methodName string,
	reqHeaders map[string]string,
	req, resp RWTStruct,
) (success bool, resHeaders map[string]string, err error)

Call makes a RPC call to the given service.

type RouterEndpoint

type RouterEndpoint struct {
	EndpointName string
	HandlerName  string
	HandlerFn    HandlerFn
	// contains filtered or unexported fields
}

RouterEndpoint struct represents an endpoint that can be registered into the router itself.

func NewRouterEndpoint

func NewRouterEndpoint(
	logger *zap.Logger,
	scope tally.Scope,
	tracer opentracing.Tracer,
	endpointID string,
	handlerID string,
	handler HandlerFn,
) *RouterEndpoint

NewRouterEndpoint creates an endpoint with all the necessary data

func (*RouterEndpoint) HandleRequest

func (endpoint *RouterEndpoint) HandleRequest(
	w http.ResponseWriter,
	r *http.Request,
	params httprouter.Params,
)

HandleRequest is called by the router and starts the request

type RuntimeMetricsCollector

type RuntimeMetricsCollector interface {
	Start()
	Stop()
	IsRunning() bool
}

RuntimeMetricsCollector interface.

func NewRuntimeMetricsCollector

func NewRuntimeMetricsCollector(
	opts RuntimeMetricsOptions,
	scope tally.Scope,
) RuntimeMetricsCollector

NewRuntimeMetricsCollector creates a new runtime metrics collector.

func StartRuntimeMetricsCollector

func StartRuntimeMetricsCollector(
	config RuntimeMetricsOptions,
	scope tally.Scope,
) RuntimeMetricsCollector

StartRuntimeMetricsCollector starts collecting runtime metrics periodically. Recommended usage:

rm := StartRuntimeMetricsCollector(rootScope.Scope("runtime"), opts)
...
rm.Stop()

type RuntimeMetricsOptions

type RuntimeMetricsOptions struct {
	EnableCPUMetrics bool          `json:"enableCPUMetrics"`
	EnableMemMetrics bool          `json:"enableMemMetrics"`
	EnableGCMetrics  bool          `json:"enableGCMetrics"`
	CollectInterval  time.Duration `json:"collectInterval"`
}

RuntimeMetricsOptions configuration.

type ServerHTTPHeader

type ServerHTTPHeader http.Header

ServerHTTPHeader wrapper to implement zanzibar Header interface on http.Header

func NewServerHTTPHeader

func NewServerHTTPHeader(h http.Header) ServerHTTPHeader

NewServerHTTPHeader creates a server http header

func (ServerHTTPHeader) Add

func (zh ServerHTTPHeader) Add(key string, value string)

Add appends a value for a given header.

func (ServerHTTPHeader) Ensure

func (zh ServerHTTPHeader) Ensure(keys []string, logger *zap.Logger) error

Ensure returns error if the headers do not have the given keys

func (ServerHTTPHeader) Get

func (zh ServerHTTPHeader) Get(key string) (string, bool)

Get retrieves the first string stored on a given header. Bool return value is used to distinguish between the presence of a header with golang's zerovalue string and the absence of the string.

func (ServerHTTPHeader) GetAll

func (zh ServerHTTPHeader) GetAll(key string) []string

GetAll retries all strings stored for this header.

func (ServerHTTPHeader) GetOrEmptyStr

func (zh ServerHTTPHeader) GetOrEmptyStr(key string) string

GetOrEmptyStr retrieves the first string stored on a given header or the empty string (golang's zero vlaue for string types)

func (ServerHTTPHeader) Keys

func (zh ServerHTTPHeader) Keys() []string

Keys returns a slice of header keys.

func (ServerHTTPHeader) Set

func (zh ServerHTTPHeader) Set(key string, value string)

Set sets a value for a given header, overwriting all previous values.

type ServerHTTPRequest

type ServerHTTPRequest struct {
	Logger       *zap.Logger
	EndpointName string
	HandlerName  string
	URL          *url.URL
	Method       string
	Params       httprouter.Params
	Header       Header
	// contains filtered or unexported fields
}

ServerHTTPRequest struct manages request

func NewServerHTTPRequest

func NewServerHTTPRequest(
	w http.ResponseWriter,
	r *http.Request,
	params httprouter.Params,
	endpoint *RouterEndpoint,
) *ServerHTTPRequest

NewServerHTTPRequest is helper function to alloc ServerHTTPRequest

func (*ServerHTTPRequest) CheckHeaders

func (req *ServerHTTPRequest) CheckHeaders(headers []string) bool

CheckHeaders verifies that request contains required headers.

func (*ServerHTTPRequest) CheckQueryValue

func (req *ServerHTTPRequest) CheckQueryValue(key string) bool

CheckQueryValue will check for a required query param.

func (*ServerHTTPRequest) GetQueryBool

func (req *ServerHTTPRequest) GetQueryBool(key string) (bool, bool)

GetQueryBool will return a query param as a boolean

func (*ServerHTTPRequest) GetQueryBoolList

func (req *ServerHTTPRequest) GetQueryBoolList(key string) ([]bool, bool)

GetQueryBoolList will return a query param as a list of boolean

func (*ServerHTTPRequest) GetQueryFloat64

func (req *ServerHTTPRequest) GetQueryFloat64(key string) (float64, bool)

GetQueryFloat64 will return query param key as float64

func (*ServerHTTPRequest) GetQueryFloat64List

func (req *ServerHTTPRequest) GetQueryFloat64List(key string) ([]float64, bool)

GetQueryFloat64List will return a query params as list of float64

func (*ServerHTTPRequest) GetQueryInt16

func (req *ServerHTTPRequest) GetQueryInt16(key string) (int16, bool)

GetQueryInt16 will return a query params as int16

func (*ServerHTTPRequest) GetQueryInt16List

func (req *ServerHTTPRequest) GetQueryInt16List(key string) ([]int16, bool)

GetQueryInt16List will return a query params as list of int16

func (*ServerHTTPRequest) GetQueryInt32

func (req *ServerHTTPRequest) GetQueryInt32(key string) (int32, bool)

GetQueryInt32 will return a query params as int32

func (*ServerHTTPRequest) GetQueryInt32List

func (req *ServerHTTPRequest) GetQueryInt32List(key string) ([]int32, bool)

GetQueryInt32List will return a query params as list of int32

func (*ServerHTTPRequest) GetQueryInt64

func (req *ServerHTTPRequest) GetQueryInt64(key string) (int64, bool)

GetQueryInt64 will return a query param as int64

func (*ServerHTTPRequest) GetQueryInt64List

func (req *ServerHTTPRequest) GetQueryInt64List(key string) ([]int64, bool)

GetQueryInt64List will return a query params as list of int64

func (*ServerHTTPRequest) GetQueryInt8

func (req *ServerHTTPRequest) GetQueryInt8(key string) (int8, bool)

GetQueryInt8 will return a query params as int8

func (*ServerHTTPRequest) GetQueryInt8List

func (req *ServerHTTPRequest) GetQueryInt8List(key string) ([]int8, bool)

GetQueryInt8List will return a query params as list of int8

func (*ServerHTTPRequest) GetQueryValue

func (req *ServerHTTPRequest) GetQueryValue(key string) (string, bool)

GetQueryValue will return the first query parameter for key or empty string

func (*ServerHTTPRequest) GetQueryValues

func (req *ServerHTTPRequest) GetQueryValues(key string) ([]string, bool)

GetQueryValues will return all query parameters for key.

func (*ServerHTTPRequest) GetRawBody

func (req *ServerHTTPRequest) GetRawBody() []byte

GetRawBody returns raw body of request

func (*ServerHTTPRequest) GetSpan

func (req *ServerHTTPRequest) GetSpan() opentracing.Span

GetSpan returns the http request span

func (*ServerHTTPRequest) HasQueryPrefix

func (req *ServerHTTPRequest) HasQueryPrefix(prefix string) bool

HasQueryPrefix will check if any query param starts with key.

func (*ServerHTTPRequest) HasQueryValue

func (req *ServerHTTPRequest) HasQueryValue(key string) bool

HasQueryValue will return bool if the query param exists.

func (*ServerHTTPRequest) PeekBody

func (req *ServerHTTPRequest) PeekBody(
	keys ...string,
) ([]byte, jsonparser.ValueType, error)

PeekBody allows for inspecting a key path inside the body that is not flushed yet. This is useful for response middlewares that want to inspect the response body.

func (*ServerHTTPRequest) ReadAll

func (req *ServerHTTPRequest) ReadAll() ([]byte, bool)

ReadAll helper to read entire body

func (*ServerHTTPRequest) ReadAndUnmarshalBody

func (req *ServerHTTPRequest) ReadAndUnmarshalBody(
	body json.Unmarshaler,
) bool

ReadAndUnmarshalBody will try to unmarshal into struct or fail

func (*ServerHTTPRequest) UnmarshalBody

func (req *ServerHTTPRequest) UnmarshalBody(
	body json.Unmarshaler, rawBody []byte,
) bool

UnmarshalBody helper to unmarshal body into struct

type ServerHTTPResponse

type ServerHTTPResponse struct {
	Request    *ServerHTTPRequest
	StatusCode int
	// contains filtered or unexported fields
}

ServerHTTPResponse struct manages request

func NewServerHTTPResponse

func NewServerHTTPResponse(
	w http.ResponseWriter,
	req *ServerHTTPRequest,
) *ServerHTTPResponse

NewServerHTTPResponse is helper function to alloc ServerHTTPResponse

func (*ServerHTTPResponse) GetPendingResponse

func (res *ServerHTTPResponse) GetPendingResponse() ([]byte, int)

GetPendingResponse lets you read the pending body bytes, obj and status code which isn't sent back yet.

func (*ServerHTTPResponse) PeekBody

func (res *ServerHTTPResponse) PeekBody(
	keys ...string,
) ([]byte, jsonparser.ValueType, error)

PeekBody allows for inspecting a key path inside the body that is not flushed yet. This is useful for response middlewares that want to inspect the response body.

func (*ServerHTTPResponse) SendError

func (res *ServerHTTPResponse) SendError(
	statusCode int, errMsg string, errCause error,
)

SendError helper to send an server error message, propagates underlying cause to logs etc.

func (*ServerHTTPResponse) SendErrorString

func (res *ServerHTTPResponse) SendErrorString(
	statusCode int, errMsg string,
)

SendErrorString helper to send an error string

func (*ServerHTTPResponse) WriteJSON

func (res *ServerHTTPResponse) WriteJSON(
	statusCode int, headers Header, body json.Marshaler,
)

WriteJSON writes a json serializable struct to Response

func (*ServerHTTPResponse) WriteJSONBytes

func (res *ServerHTTPResponse) WriteJSONBytes(
	statusCode int, headers Header, bytes []byte,
)

WriteJSONBytes writes a byte[] slice that is valid json to Response

type ServerTChannelHeader

type ServerTChannelHeader map[string]string

ServerTChannelHeader wrapper to implement zanzibar Header interface on map[string]string Unlike http.Header, tchannel headers are case sensitive and should be keyed with lower case. TChannel protocol does not mention header case sensitivity, so it is up to implementation.

func (ServerTChannelHeader) Add

func (th ServerTChannelHeader) Add(key string, value string)

Add is an alias to Set.

func (ServerTChannelHeader) Ensure

func (th ServerTChannelHeader) Ensure(keys []string, logger *zap.Logger) error

Ensure returns error if the headers do not have the given keys

func (ServerTChannelHeader) Get

func (th ServerTChannelHeader) Get(key string) (string, bool)

Get retrieves the string value stored on a given header. Bool return value is used to distinguish between the presence of a header with golang's zerovalue string and the absence of the string.

func (ServerTChannelHeader) Keys

func (th ServerTChannelHeader) Keys() []string

Keys returns a slice of header keys.

func (ServerTChannelHeader) Set

func (th ServerTChannelHeader) Set(key string, value string)

Set sets a value for a given header, overwriting the previous value.

type SharedState

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

SharedState used to access other middlewares in the chain.

func NewSharedState

func NewSharedState(middlewares []MiddlewareHandle) SharedState

NewSharedState constructs a ShardState

func (SharedState) GetState

func (s SharedState) GetState(name string) interface{}

GetState returns the state from a different middleware

func (SharedState) SetState

func (s SharedState) SetState(m MiddlewareHandle, state interface{})

SetState sets value of a middleware shared state

type StaticConfig

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

StaticConfig allows accessing values out of json config files

func NewStaticConfigOrDie

func NewStaticConfigOrDie(
	configOptions []*ConfigOption,
	seedConfig map[string]interface{},
) *StaticConfig

NewStaticConfigOrDie allocates a static config instance StaticConfig takes two args, files and seedConfig.

files is required and must be a list of file paths. The later files overwrite keys from earlier files.

The seedConfig is optional and will be used to overwrite configuration json files if present.

The defaultConfig is optional initial config that will be overwritten by the config in the supplied files or the seed config

The files must be a list of JSON files. Each file must be a flat object of key, value pairs. It's recommended that you use keys like:

{
    "name": "my-name",
    "clients.thingy": {
         "some client": "config"
    },
    "server.my-port": 9999
}

To organize your configuration file.

func (*StaticConfig) ContainsKey

func (conf *StaticConfig) ContainsKey(key string) bool

ContainsKey returns true if key is found otherwise false.

func (*StaticConfig) Destroy

func (conf *StaticConfig) Destroy()

Destroy will make Get() calls fail with a panic. This allows you to terminate the configuration phase and gives you confidence that your application is now officially bootstrapped.

func (*StaticConfig) Freeze

func (conf *StaticConfig) Freeze()

Freeze the configuration store. Once you freeze the config any further calls to config.set() will panic. This allows you to make the static config immutable

func (*StaticConfig) InspectOrDie

func (conf *StaticConfig) InspectOrDie() map[string]interface{}

InspectOrDie returns the entire config object. This should not be mutated and should only be used for inspection or debugging

func (*StaticConfig) MustGetBoolean

func (conf *StaticConfig) MustGetBoolean(key string) bool

MustGetBoolean returns the value as a boolean or panics.

func (*StaticConfig) MustGetFloat

func (conf *StaticConfig) MustGetFloat(key string) float64

MustGetFloat returns the value as a float or panics.

func (*StaticConfig) MustGetInt

func (conf *StaticConfig) MustGetInt(key string) int64

MustGetInt returns the value as a int or panics.

func (*StaticConfig) MustGetString

func (conf *StaticConfig) MustGetString(key string) string

MustGetString returns the value as a string or panics.

func (*StaticConfig) MustGetStruct

func (conf *StaticConfig) MustGetStruct(key string, ptr interface{})

MustGetStruct reads the value into an interface{} or panics. Recommended that this is used with pointers to structs MustGetStruct() will call json.Unmarshal(bytes, ptr) under the hood.

func (*StaticConfig) SetConfigValueOrDie

func (conf *StaticConfig) SetConfigValueOrDie(key string, bytes []byte, dataType string)

SetConfigValueOrDie sets the static config value. dataType can be a boolean, number or string. SetConfigValueOrDie will panic if the config is frozen.

func (*StaticConfig) SetSeedOrDie

func (conf *StaticConfig) SetSeedOrDie(key string, value interface{})

SetSeedOrDie a value in the config, useful for tests. Keys you set must not exist in the JSON files. Set() will panic if the key exists or if frozen. Strongly recommended not to be used for production code.

type StaticConfigValue

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

StaticConfigValue represents a json serialized string.

type TChannelCaller

type TChannelCaller interface {
	// Call should be passed the method to call, headers and the request/response thriftrw structs.
	// The arguments returned are (whether there was an application error, unexpected error)
	Call(ctx context.Context, service, method string, reqHeaders map[string]string, req, resp RWTStruct) (success bool, respHeaders map[string]string, err error)
}

TChannelCaller abstracts calling a Thrift endpoint, and is used by the generated client code.

type TChannelClient

type TChannelClient struct {
	ClientID string

	Loggers map[string]*zap.Logger
	Scopes  map[string]tally.Scope
	// contains filtered or unexported fields
}

TChannelClient implements TChannelCaller and makes outgoing Thrift calls.

func NewTChannelClient

func NewTChannelClient(
	ch *tchannel.Channel,
	logger *zap.Logger,
	scope tally.Scope,
	opt *TChannelClientOption,
) *TChannelClient

NewTChannelClient returns a TChannelClient that makes calls over the given tchannel to the given thrift service.

func (*TChannelClient) Call

func (c *TChannelClient) Call(
	ctx context.Context,
	thriftService, methodName string,
	reqHeaders map[string]string,
	req, resp RWTStruct,
) (success bool, resHeaders map[string]string, err error)

Call makes a RPC call to the given service.

func (*TChannelClient) CallThruAltChannel

func (c *TChannelClient) CallThruAltChannel(
	ctx context.Context,
	thriftService, methodName string,
	reqHeaders map[string]string,
	req, resp RWTStruct,
) (success bool, resHeaders map[string]string, err error)

CallThruAltChannel makes a RPC call using a configured alternate channel

type TChannelClientOption

type TChannelClientOption struct {
	ServiceName       string
	ClientID          string
	Timeout           time.Duration
	TimeoutPerAttempt time.Duration
	RoutingKey        *string

	// MethodNames is a map from "ThriftService::method" to "ZanzibarMethodName",
	// where ThriftService and method are from the service's Thrift IDL, and
	// ZanzibarMethodName is the public method name exposed on the Zanzibar-generated
	// client, from the zanzibar configuration. For example, if a client named FooClient
	// has a methodMap of map[string]string{"Foo::bar":"Bar"}, then one can do
	// `FooClient.Bar()` to issue a RPC to Thrift service `Foo`'s `bar` method.
	MethodNames map[string]string

	// An alternate subchannel that can optionally be used to make a TChannel call
	// instead; e.g. can allow the service to be overridden when a "X-Zanzibar-Use-Staging"
	// header is present
	AltSubchannelName string
}

TChannelClientOption is used when creating a new TChannelClient

type TChannelEndpoint

type TChannelEndpoint struct {
	TChannelHandler

	EndpointID string
	HandlerID  string
	Method     string

	Logger *zap.Logger
	Scope  tally.Scope
	// contains filtered or unexported fields
}

TChannelEndpoint handles tchannel requests

func NewTChannelEndpoint

func NewTChannelEndpoint(
	logger *zap.Logger,
	scope tally.Scope,
	endpointID, handlerID, method string,
	handler TChannelHandler,
) *TChannelEndpoint

NewTChannelEndpoint creates a new tchannel endpoint to handle an incoming call for its method.

func NewTChannelEndpointWithPostResponseCB

func NewTChannelEndpointWithPostResponseCB(
	logger *zap.Logger,
	scope tally.Scope,
	endpointID, handlerID, method string,
	handler TChannelHandler,
	callback PostResponseCB,
) *TChannelEndpoint

NewTChannelEndpointWithPostResponseCB creates a new tchannel endpoint, with or without a post response callback function.

type TChannelHandler

type TChannelHandler interface {
	// Handle should read the request from the given reqReader, and return the response struct.
	// The arguments returned are (whether there was an application error, response headers, result struct, unexpected error)
	Handle(ctx context.Context, reqHeaders map[string]string, wireValue *wire.Value) (success bool, resp RWTStruct, respHeaders map[string]string, err error)
}

TChannelHandler abstracts handling of an RPC that is implemented by the generated server code.

type TChannelLogger

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

TChannelLogger warps a zap logger to be used for TChannel internal logging

func (TChannelLogger) Debug

func (l TChannelLogger) Debug(msg string)

Debug logs a message at debug priority.

func (TChannelLogger) Debugf

func (l TChannelLogger) Debugf(msg string, args ...interface{})

Debugf logs a message at debug priority.

func (TChannelLogger) Enabled

func (l TChannelLogger) Enabled(tlevel tchannel.LogLevel) bool

Enabled returns whether the given level is enabled.

func (TChannelLogger) Error

func (l TChannelLogger) Error(msg string)

Error logs a message at error priority.

func (TChannelLogger) Fatal

func (l TChannelLogger) Fatal(msg string)

Fatal logs a message, then exits with os.Exit(1).

func (TChannelLogger) Fields

func (l TChannelLogger) Fields() tchannel.LogFields

Fields returns the fields that this logger contains.

func (TChannelLogger) Info

func (l TChannelLogger) Info(msg string)

Info logs a message at info priority.

func (TChannelLogger) Infof

func (l TChannelLogger) Infof(msg string, args ...interface{})

Infof logs a message at info priority.

func (TChannelLogger) Warn

func (l TChannelLogger) Warn(msg string)

Warn logs a message at warning priority.

func (TChannelLogger) WithFields

func (l TChannelLogger) WithFields(fields ...tchannel.LogField) tchannel.Logger

WithFields returns a logger with the current logger's fields and fields.

type TChannelRouter

type TChannelRouter struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

TChannelRouter handles incoming TChannel calls and routes them to the matching TChannelHandler.

func NewTChannelRouter

func NewTChannelRouter(registrar tchannel.Registrar, g *Gateway) *TChannelRouter

NewTChannelRouter returns a TChannel router that can serve thrift services over TChannel.

func (*TChannelRouter) Handle

func (s *TChannelRouter) Handle(ctx context.Context, call *tchannel.InboundCall)

Handle handles an incoming TChannel call and forwards it to the correct handler.

func (*TChannelRouter) Register

func (s *TChannelRouter) Register(e *TChannelEndpoint) error

Register registers the given TChannelEndpoint.

type TchannelSharedState

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

TchannelSharedState used to access other middlewares in the chain.

func NewTchannelSharedState

func NewTchannelSharedState(middlewares []MiddlewareTchannelHandle) TchannelSharedState

NewTchannelSharedState constructs a ShardState

func (TchannelSharedState) GetTchannelState

func (s TchannelSharedState) GetTchannelState(name string) interface{}

GetTchannelState returns the state from a different middleware

func (TchannelSharedState) SetTchannelState

func (s TchannelSharedState) SetTchannelState(m MiddlewareTchannelHandle, state interface{})

SetTchannelState sets value of a middleware shared state

type UnexpectedHTTPError

type UnexpectedHTTPError struct {
	StatusCode int
	RawBody    []byte
}

UnexpectedHTTPError defines an error for HTTP

func (*UnexpectedHTTPError) Error

func (rawErr *UnexpectedHTTPError) Error() string

Jump to

Keyboard shortcuts

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