zanzibar

package
v2.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2023 License: MIT Imports: 50 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// MetricEndpointPanics is endpoint level panic counter
	MetricEndpointPanics = "endpoint.panic"

	// MetricEndpointAppErrors is the metric name for endpoint level application error for TChannel
	MetricEndpointAppErrors = "endpoint.app-errors"

	// HTTPStatusClientClosedRequest code describes client closed request as per this doc https://httpstatus.in/499/
	HTTPStatusClientClosedRequest = 499

	// TraceIDKey is the log field key containing the associated trace id
	TraceIDKey = "trace.traceId"
	// TraceSpanKey is the log field key containing the associated span id
	TraceSpanKey = "trace.span"
	// TraceSampledKey is the log field key for whether a trace was sampled or not
	TraceSampledKey = "trace.sampled"

	// ClientResponseDurationKey is the key denoting a downstream response duration
	ClientResponseDurationKey = "client.response.duration"
	// ClientTypeKey denotes the type of the client, usually http / tchannel / client-less / custom
	ClientTypeKey = "client.type"
)
View Source
const (
	EventThriftOutgoing = "event-thrift-outgoing"
	EventHTTPIncoming   = "event-http-incoming"
	EventHTTPOutgoing   = "event-http-outgoing"
)
View Source
const (
	// ToCapture set to true if events have to be captured
	ToCapture = "to_capture"
)

Context Variables

Variables

DefaultBackOffTimeAcrossRetries is the time in MS to wait before attempting new attempt

View Source
var DefaultBackOffTimeAcrossRetriesConf = 10

DefaultBackOffTimeAcrossRetriesConf is the time to wait before attempting new attempt

View Source
var DefaultScaleFactor = 1.1

DefaultScaleFactor is multiplied with timeoutPerAttempt

View Source
var LogFieldErrTypeClientException = LogFieldErrorType("client_exception")

LogFieldErrTypeClientException is a log field used to tag errors corresponding to exceptions defined in client thrifts.

Functions

func AppendLogFieldsToContext

func AppendLogFieldsToContext(ctx context.Context, fields ...zap.Field)

AppendLogFieldsToContext is safe to use concurrently. It doesn't require caller to update the context. The context should have safeLogFields value set using WithSafeLogFields (or WithLogFields for backward compatibility) before.

func DefaultRetryPolicy

func DefaultRetryPolicy(ctx context.Context, timeoutAndRetryOptions *TimeoutAndRetryOptions, resp *http.Response, err error) bool

DefaultRetryPolicy allows retries for any type of server error

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 GetAPIEnvironment

func GetAPIEnvironment(endpoint *RouterEndpoint, r *http.Request) string

GetAPIEnvironment returns the api environment for a given request. By default, the api environment is set to production. However, there may be use cases where a different environment may be required for monitoring purposes. This may be overridden by a non-empty environment value in the request header.

func GetAccumulatedLogContext

func GetAccumulatedLogContext(ctx context.Context, c *contextLogger, msg string, logLevel zapcore.Level, userFields ...zap.Field) context.Context

GetAccumulatedLogContext returns accumulated log context

func GetBuffer

func GetBuffer() *bytes.Buffer

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

func GetCtxLogCounterFromCtx

func GetCtxLogCounterFromCtx(ctx context.Context) int

GetCtxLogCounterFromCtx returns ctxLogCounter value from ctx

func GetCtxLogLevelOrDebugLevelFromCtx

func GetCtxLogLevelOrDebugLevelFromCtx(ctx context.Context) zapcore.Level

GetCtxLogLevelOrDebugLevelFromCtx returns ctxLogLevel value from ctx

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 GetEndpointRequestHeadersFromCtx

func GetEndpointRequestHeadersFromCtx(ctx context.Context) map[string]string

GetEndpointRequestHeadersFromCtx returns the endpoint request headers, if it exists on context

func GetHostname

func GetHostname() string

GetHostname returns hostname

func GetLogFieldsFromCtx

func GetLogFieldsFromCtx(ctx context.Context) []zap.Field

GetLogFieldsFromCtx returns the log fields attached to the context.Context

func GetRequestEndpointFromCtx

func GetRequestEndpointFromCtx(ctx context.Context) string

GetRequestEndpointFromCtx returns the endpoint, if it exists on context

func GetRoutingDelegateFromCtx

func GetRoutingDelegateFromCtx(ctx context.Context) string

GetRoutingDelegateFromCtx returns the tchannel routing delegate info extracted from context.

func GetScopeTagsFromCtx

func GetScopeTagsFromCtx(ctx context.Context) map[string]string

GetScopeTagsFromCtx returns the tag info extracted from context.

func GetShardKeyFromCtx

func GetShardKeyFromCtx(ctx context.Context) string

GetShardKeyFromCtx returns the tchannel shardkey info extracted from context.

func GetToCapture added in v2.0.4

func GetToCapture(ctx context.Context) bool

GetToCapture returns the stored event

func LogErrorWarnTimeout deprecated

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

Deprecated: use proper level to log instead

func LogFieldErrorLocation

func LogFieldErrorLocation(loc string) zap.Field

LogFieldErrorLocation returns error_location log field with given value.

func LogFieldErrorType

func LogFieldErrorType(errType string) zap.Field

LogFieldErrorType returns error_type log field with given value.

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 NoOpEventHandler added in v2.0.4

func NoOpEventHandler(events []Event) error

NoOpEventHandler ignored events

func NoOpEventSampler added in v2.0.4

func NoOpEventSampler(_, _ string) bool

NoOpEventSampler will not sample

func ParamsFromContext

func ParamsFromContext(ctx context.Context) url.Values

ParamsFromContext extracts the URL parameters that are embedded in the context by the Zanzibar HTTP router implementation.

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 RequestUUIDFromCtx

func RequestUUIDFromCtx(ctx context.Context) string

RequestUUIDFromCtx returns the RequestUUID, if it exists on context

func WithEndpointField

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

WithEndpointField adds the endpoint information in the request context.

func WithEndpointRequestHeadersField

func WithEndpointRequestHeadersField(ctx context.Context, requestHeaders map[string]string) context.Context

WithEndpointRequestHeadersField adds the endpoint request header information in the request context.

func WithEventContainer added in v2.0.4

func WithEventContainer(ctx context.Context, ec *EventContainer) context.Context

WithEventContainer stores an event in the context. Use it only when the request is expected to generate a single event

func WithLogFields deprecated

func WithLogFields(ctx context.Context, newFields ...zap.Field) context.Context

WithLogFields returns a new context with the given log fields attached to context.Context

Deprecated: See AppendLogFieldsToContext.

func WithRoutingDelegate

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

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

func WithSafeLogFields

func WithSafeLogFields(ctx context.Context) context.Context

WithSafeLogFields initiates empty safeLogFields in the context.

func WithScopeTags

func WithScopeTags(ctx context.Context, fields map[string]string) context.Context

WithScopeTags adds tags to context without updating the scope

func WithScopeTagsDefault

func WithScopeTagsDefault(ctx context.Context, fields map[string]string, defaultScope tally.Scope) context.Context

WithScopeTagsDefault returns a new context with the given scope tags attached to context.Context This operation adds the fields and updates scope in context. defaultScope when scopeData is stored for the first time

func WithShardKey

func WithShardKey(ctx context.Context, sk string) context.Context

WithShardKey adds the tchannel shard key information in the request context.

func WithTimeAndRetryOptions

func WithTimeAndRetryOptions(ctx context.Context, tro *TimeoutAndRetryOptions) context.Context

WithTimeAndRetryOptions returns a context with timeout and retry options.

func WithToCapture added in v2.0.4

func WithToCapture(ctx context.Context) context.Context

WithToCapture sets event capture on for a 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 CheckRetry

type CheckRetry func(ctx context.Context, timeoutAndRetryOptions *TimeoutAndRetryOptions, resp *http.Response, err error) bool

CheckRetry specifies a policy for handling retries. It is called following each request with the response and error values returned by the http.Client. If CheckRetry returns false, the Client stops retrying and returns the response to the caller. If CheckRetry returns an error, that error value is returned in lieu of the error from the request.

type ClientHTTPRequest

type ClientHTTPRequest struct {
	ClientID             string
	ClientTargetEndpoint string
	MethodName           string
	Metrics              ContextMetrics

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

ClientHTTPRequest is the struct for making a single client request using an outbound http client.

func NewClientHTTPRequest

func NewClientHTTPRequest(
	ctx context.Context,
	clientID string,
	clientMethod string,
	clientTargetEndpoint string,
	client *HTTPClient,
) *ClientHTTPRequest

NewClientHTTPRequest allocates a ClientHTTPRequest. The ctx parameter is the context associated with the outbound requests.

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) WriteBytes

func (req *ClientHTTPRequest) WriteBytes(
	method, url string,
	headers map[string]string,
	rawBody []byte,
) error

WriteBytes materialize the HTTP request with given method, url, headers and body. Body is assumed to be a byte array.s

func (*ClientHTTPRequest) WriteJSON

func (req *ClientHTTPRequest) WriteJSON(
	method, url string,
	headers map[string]string,
	body interface{},
) error

WriteJSON materialize the HTTP request with given method, url, headers and body.

type ClientHTTPResponse

type ClientHTTPResponse struct {
	StatusCode int
	Duration   time.Duration
	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

func (*ClientHTTPResponse) ReadAndUnmarshalBodyMultipleOptions

func (res *ClientHTTPResponse) ReadAndUnmarshalBodyMultipleOptions(vs []interface{}) (interface{}, error)

ReadAndUnmarshalBodyMultipleOptions will try to unmarshal non pointer value to one of the provided types or fail It will return the deserialized struct (if any) that succeeded

func (*ClientHTTPResponse) UnmarshalBody

func (res *ClientHTTPResponse) UnmarshalBody(v interface{}, rawBody []byte) error

UnmarshalBody helper to unmarshal body into struct

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 ContextExtractor

type ContextExtractor interface {
	ExtractScopeTags(ctx context.Context) map[string]string
	ExtractLogFields(ctx context.Context) []zap.Field
}

ContextExtractor is a extractor that extracts some log fields from the context

type ContextExtractors

type ContextExtractors struct {
	ScopeTagsExtractors []ContextScopeTagsExtractor
	LogFieldsExtractors []ContextLogFieldsExtractor
}

ContextExtractors warps extractors for context, implements ContextExtractor interface

func (*ContextExtractors) ExtractLogFields

func (c *ContextExtractors) ExtractLogFields(ctx context.Context) []zap.Field

ExtractLogFields extracts log fields from a context into a field.

func (*ContextExtractors) ExtractScopeTags

func (c *ContextExtractors) ExtractScopeTags(ctx context.Context) map[string]string

ExtractScopeTags extracts scope fields from a context into a tag.

type ContextLogFieldsExtractor

type ContextLogFieldsExtractor func(context.Context) []zap.Field

ContextLogFieldsExtractor defines func where extracts log fields from context

type ContextLogger

type ContextLogger interface {
	Debug(ctx context.Context, msg string, fields ...zap.Field) context.Context
	Error(ctx context.Context, msg string, fields ...zap.Field) context.Context
	Info(ctx context.Context, msg string, fields ...zap.Field) context.Context
	Panic(ctx context.Context, msg string, fields ...zap.Field) context.Context
	Warn(ctx context.Context, msg string, fields ...zap.Field) context.Context

	// DebugZ skips logs, and adds to context if skipZanzibarLogs is set to true otherwise behaves as normal Debug, similarly for other XxxxZ's
	DebugZ(ctx context.Context, msg string, fields ...zap.Field) context.Context
	ErrorZ(ctx context.Context, msg string, fields ...zap.Field) context.Context
	InfoZ(ctx context.Context, msg string, fields ...zap.Field) context.Context
	PanicZ(ctx context.Context, msg string, fields ...zap.Field) context.Context
	WarnZ(ctx context.Context, msg string, fields ...zap.Field) context.Context

	// Other utility methods on the logger
	Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry

	SetSkipZanzibarLogs(bool)
}

ContextLogger is a logger that extracts some log fields from the context before passing through to underlying zap logger. In cases it also updates the context instead of logging

func NewContextLogger

func NewContextLogger(log *zap.Logger) ContextLogger

NewContextLogger returns a logger that extracts log fields a context before passing through to underlying zap logger.

type ContextMetrics

type ContextMetrics interface {
	Scope() tally.Scope
	IncCounter(ctx context.Context, name string, value int64)
	RecordTimer(ctx context.Context, name string, d time.Duration)
	RecordHistogramDuration(ctx context.Context, name string, d time.Duration)
}

ContextMetrics emit metrics with tags extracted from context. This interface is now deprecated.

func NewContextMetrics

func NewContextMetrics(scope tally.Scope) ContextMetrics

NewContextMetrics create ContextMetrics to emit metrics with tags extracted from context.

type ContextScopeTagsExtractor

type ContextScopeTagsExtractor func(context.Context) map[string]string

ContextScopeTagsExtractor defines func where extracts tags from context

type DefaultDependencies

type DefaultDependencies struct {
	// ContextExtractor extracts context for scope and logs field
	ContextExtractor ContextExtractor
	// ContextLogger is a logger with request-scoped log fields
	ContextLogger ContextLogger
	// ContextMetrics emit metrics from context
	ContextMetrics ContextMetrics

	Logger         *zap.Logger
	Scope          tally.Scope
	Tracer         opentracing.Tracer
	Config         *StaticConfig
	ServerTChannel *tchannel.Channel
	Gateway        *Gateway

	// dispatcher for managing gRPC clients
	GRPCClientDispatcher *yarpc.Dispatcher

	// JSONWrapper provides json marshaling and unmarshaling functionality
	JSONWrapper jsonwrapper.JSONWrapper
}

DefaultDependencies are the common dependencies for all modules

type Event added in v2.0.4

type Event interface {
	Name() string
}

type EventContainer added in v2.0.4

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

EventContainer holds generated events.

func GetEventContainer added in v2.0.4

func GetEventContainer(ctx context.Context) *EventContainer

GetEventContainer returns the stored event

type EventHandlerFn added in v2.0.4

type EventHandlerFn func([]Event) error

type EventSamplerFn added in v2.0.4

type EventSamplerFn func(string, string) bool

type GRPCClientCallHelper

type GRPCClientCallHelper interface {
	// Start method should be used just before calling the actual gRPC client method call.
	Start()
	// Finish method should be used right after the actual call to gRPC client method.
	Finish(ctx context.Context, err error) context.Context
}

GRPCClientCallHelper is used to track internal state of logging and metrics.

func NewGRPCClientCallHelper

func NewGRPCClientCallHelper(ctx context.Context, serviceMethod string, opts *GRPCClientOpts) (context.Context, GRPCClientCallHelper)

NewGRPCClientCallHelper used to initialize a helper that will be used to track logging and metric for a gRPC Client call.

type GRPCClientOpts

type GRPCClientOpts struct {
	ContextLogger          ContextLogger
	Metrics                ContextMetrics
	ContextExtractor       ContextExtractor
	RoutingKey             string
	RequestUUIDHeaderKey   string
	CircuitBreakerDisabled bool
	Timeout                time.Duration
	ScopeTags              map[string]map[string]string
}

GRPCClientOpts used to configure various client options.

func NewGRPCClientOpts

func NewGRPCClientOpts(
	contextLogger ContextLogger,
	metrics ContextMetrics,
	contextExtractor ContextExtractor,
	methodNames map[string]string,
	clientID, routingKey, requestUUIDHeaderKey string,
	circuitBreakerDisabled bool,
	timeoutInMS int,
) *GRPCClientOpts

NewGRPCClientOpts creates a new instance of GRPCClientOpts.

type Gateway

type Gateway struct {
	HTTPPort               int32
	TChannelPort           int32
	RealHTTPPort           int32
	RealHTTPAddr           string
	RealTChannelPort       int32
	RealTChannelAddr       string
	WaitGroup              *sync.WaitGroup
	ServerTChannel         *tchannel.Channel
	ClientTChannels        map[string]*tchannel.Channel
	ContextLogger          ContextLogger
	ContextMetrics         ContextMetrics
	ContextExtractor       ContextExtractor
	RootScope              tally.Scope
	Logger                 *zap.Logger
	ServiceName            string
	Config                 *StaticConfig
	HTTPRouter             HTTPRouter
	ServerTChannelRouter   *TChannelRouter
	TChannelSubLoggerLevel zapcore.Level
	Tracer                 opentracing.Tracer
	JSONWrapper            jsonwrapper.JSONWrapper
	EventHandler           EventHandlerFn
	EventSampler           EventSamplerFn
	// gRPC client dispatcher for gRPC client lifecycle management
	GRPCClientDispatcher *yarpc.Dispatcher
	// 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) SetupClientTChannel

func (gateway *Gateway) SetupClientTChannel(config *StaticConfig, serviceName string) *tchannel.Channel

SetupClientTChannel sets up a dedicated tchannel for each client with a given service name If multiple backends with the same service name exist (for e.g. presentation service), then all of them would receive the same channel. The method is exported because it is called from the generated clients if "dedicated.tchannel.client: true" else server tchannel is reused

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 HTTPCapture added in v2.0.4

type HTTPCapture struct {
	ReqURL     string
	ReqMethod  string
	ReqHeaders map[string][]string
	ReqBody    []byte

	RspStatusCode int
	RspMethod     string
	RspHeaders    map[string][]string
	RspBody       []byte
}

HTTPCapture captures request and response data

type HTTPClient

type HTTPClient struct {
	Client         *http.Client
	BaseURL        string
	DefaultHeaders map[string]string
	JSONWrapper    jsonwrapper.JSONWrapper
	ContextLogger  ContextLogger

	CheckRetry CheckRetry
	// contains filtered or unexported fields
}

HTTPClient defines a http client.

func NewHTTPClient

func NewHTTPClient(
	contextLogger ContextLogger,
	scope tally.Scope,
	jsonWrapper jsonwrapper.JSONWrapper,
	clientID string,
	methodToTargetEndpoint map[string]string,
	baseURL string,
	defaultHeaders map[string]string,
	timeout time.Duration,
) *HTTPClient

NewHTTPClient is deprecated, use NewHTTPClientContext instead

func NewHTTPClientContext

func NewHTTPClientContext(
	contextLogger ContextLogger,
	ContextMetrics ContextMetrics,
	jsonWrapper jsonwrapper.JSONWrapper,
	clientID string,
	methodToTargetEndpoint map[string]string,
	baseURL string,
	defaultHeaders map[string]string,
	timeout time.Duration,
	followRedirect bool,
) *HTTPClient

NewHTTPClientContext will allocate a http client.

type HTTPIncomingEvent added in v2.0.4

type HTTPIncomingEvent struct {
	EndpointName string // optional
	HandlerName  string // optional

	HTTPCapture
}

HTTPIncomingEvent captures incoming request and response data received

func (*HTTPIncomingEvent) Name added in v2.0.4

func (hce *HTTPIncomingEvent) Name() string

type HTTPOutgoingEvent added in v2.0.4

type HTTPOutgoingEvent struct {
	ClientID       string // optional
	ClientEndpoint string // optional

	HTTPCapture
}

HTTPOutgoingEvent captures incoming request and response data received

func (*HTTPOutgoingEvent) Name added in v2.0.4

func (hce *HTTPOutgoingEvent) Name() string

type HTTPRouter

type HTTPRouter interface {
	// HTTPRouter implements a http.Handle as a convenience to allow HTTPRouter to be invoked by the standard library HTTP server.
	http.Handler

	// Handle associates a HTTP method and a pattern string to a HTTP handler function. If the method and pattern string
	// already exists, an error is returned.
	Handle(method, pattern string, handler http.Handler) error
}

HTTPRouter provides a HTTP router. It will match patterns in URLs and route them to provided HTTP handlers.

This router has support for decoding path "parameters" in the URL into named values. An example:

var r zanzibar.HTTPRouter

r.Handle("GET", "/foo/:bar", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    params := zanzibar.ParamsFromContext(r.Context())
    w.Write("%s", params.Get("bar"))
}))

func NewHTTPRouter

func NewHTTPRouter(gateway *Gateway) HTTPRouter

NewHTTPRouter allocates a HTTP router

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 HandlerFn

HandlerFn is a func that handles ServerHTTPRequest

type Header interface {
	// Get mirrors the implementation of http.header and returns a single header value.
	// When a key contains multiple values, -only- the first one is returned.
	// Ref: https://golang.org/pkg/net/http/#Header.Get
	Get(key string) (string, bool)
	// Values mirrors the implementation of http.header and returns a slice of header values.
	// When a key contains multiple values, the entire collection is returned.
	// Ref: https://golang.org/pkg/net/http/#Header.Values
	Values(key string) ([]string, bool)
	Add(key string, value string)
	Set(key string, value string)
	// Unset unsets the value for a given header. Can be safely called multiple times
	Unset(key string)
	Keys() []string
	// Deprecated: Use EnsureContext instead
	Ensure(keys []string, logger *zap.Logger) error
	EnsureContext(ctx context.Context, keys []string, logger ContextLogger) error
}

Header defines methods on ServerHeaders

type Logger

type Logger interface {
	Debug(msg string, fields ...zap.Field)
	Error(msg string, fields ...zap.Field)
	Info(msg string, fields ...zap.Field)
	Panic(msg string, fields ...zap.Field)
	Warn(msg string, fields ...zap.Field)
	Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry
}

Logger is a generic logger interface that zap.Logger implements.

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,
	) (context.Context, bool)
	// implement HandleResponse for your middleware. Return false
	// if the handler writes to the response body.
	HandleResponse(
		ctx context.Context,
		res *ServerHTTPResponse,
		shared SharedState,
	) context.Context
	// 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 Handle. 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) (context.Context, 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 Handle. 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) (context.Context, 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
	MetricsDefaultBuckets     tally.Buckets // To support non-default histogram metric bucketing specific to a gateway
	LogWriter                 zapcore.WriteSyncer
	GetContextScopeExtractors func() []ContextScopeTagsExtractor
	GetContextFieldExtractors func() []ContextLogFieldsExtractor
	JSONWrapper               jsonwrapper.JSONWrapper
	NotFoundHandler           func(*Gateway) http.HandlerFunc
	TracerProvider            func(*Gateway) (opentracing.Tracer, io.Closer, error)
	EventProvider             func(*Gateway) (EventSamplerFn, EventHandlerFn)
	// If present, request uuid is retrieved from the incoming request
	// headers using the key, and put on the context. Otherwise, a new
	// uuid is created for the incoming request.
	RequestUUIDHeaderKey string
}

Options configures the gateway

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,
	contextLogger ContextLogger,
	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
	JSONWrapper  jsonwrapper.JSONWrapper
	// contains filtered or unexported fields
}

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

func NewRouterEndpoint

func NewRouterEndpoint(
	extractor ContextExtractor,
	deps *DefaultDependencies,
	endpointID string,
	handlerID string,
	handler HandlerFn,
) *RouterEndpoint

NewRouterEndpoint creates an endpoint that can be registered to HTTPRouter

func (*RouterEndpoint) HandleRequest

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

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 deprecated

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

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

Deprecated: Use EnsureContext instead

func (ServerHTTPHeader) EnsureContext

func (zh ServerHTTPHeader) EnsureContext(ctx context.Context, keys []string, logger ContextLogger) error

EnsureContext 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 header.

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.

func (ServerHTTPHeader) Unset

func (zh ServerHTTPHeader) Unset(key string)

Unset unsets the value for a given header. Can be safely called multiple times

func (ServerHTTPHeader) Values

func (zh ServerHTTPHeader) Values(key string) ([]string, bool)

Values retrieves the entire collection of values stored on a given header. Bool return value is used to distinguish between the presence of a header with golang's zerovalue slice and the absence of the header.

type ServerHTTPRequest

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

ServerHTTPRequest struct manages server http request

func NewServerHTTPRequest

func NewServerHTTPRequest(
	w http.ResponseWriter,
	r *http.Request,
	params url.Values,
	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) Context

func (req *ServerHTTPRequest) Context() context.Context

Context returns the request's context.

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) GetQueryFloat64Set

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

GetQueryFloat64Set will return a query params as set 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) GetQueryInt16Set

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

GetQueryInt16Set will return a query params as set 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) GetQueryInt32Set

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

GetQueryInt32Set will return a query params as set 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) GetQueryInt64Set

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

GetQueryInt64Set will return a query params as set 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) GetQueryInt8Set

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

GetQueryInt8Set will return a query params as set of int8 (implemented as a deduped slice)

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) GetQueryValueList

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

GetQueryValueList will return all query parameters for key.

func (*ServerHTTPRequest) GetQueryValueSet

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

GetQueryValueSet will return all query parameters for key as a set

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) LogAndSendQueryError

func (req *ServerHTTPRequest) LogAndSendQueryError(err error, expected, key, value string)

LogAndSendQueryError handles parse failure of query params by logging the issue and returning a 400 to the requestor

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 interface{},
) bool

ReadAndUnmarshalBody will try to unmarshal into struct or fail

func (*ServerHTTPRequest) ReplaceBody

func (req *ServerHTTPRequest) ReplaceBody(body []byte)

ReplaceBody replaces the raw request body with given body and updates the request content-length header accordingly. This method is only supposed to be used in middlewares where request body needs to be modified. The encoding of the body should stay the same.

func (*ServerHTTPRequest) SetQueryValue

func (req *ServerHTTPRequest) SetQueryValue(key string, value string)

SetQueryValue will set the value of the query parameter, replacing any existing value We only work with one value, and not a list (in keeping with other url.Values methods)

func (*ServerHTTPRequest) StartTime

func (req *ServerHTTPRequest) StartTime() time.Time

StartTime returns the request's start time.

func (*ServerHTTPRequest) UnmarshalBody

func (req *ServerHTTPRequest) UnmarshalBody(
	body interface{}, rawBody []byte,
) bool

UnmarshalBody helper to unmarshal body into struct

type ServerHTTPResponse

type ServerHTTPResponse struct {
	Request    *ServerHTTPRequest
	StatusCode int

	DownstreamFinishTime time.Duration
	ClientType           string

	Err error
	// contains filtered or unexported fields
}

ServerHTTPResponse struct manages server http response

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) GetPendingResponseObject

func (res *ServerHTTPResponse) GetPendingResponseObject() interface{}

GetPendingResponseObject lets you read the pending body object which isn't sent back yet.

func (*ServerHTTPResponse) Headers

func (res *ServerHTTPResponse) Headers() http.Header

Headers returns the underlying http response's headers

func (*ServerHTTPResponse) MarshalResponseJSON

func (res *ServerHTTPResponse) MarshalResponseJSON(body interface{}) []byte

MarshalResponseJSON serializes a json serializable into bytes

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) SendResponse

func (res *ServerHTTPResponse) SendResponse(statusCode int, headers Header, body interface{}, bytes []byte)

SendResponse sets content-type if not present and fills Response

func (*ServerHTTPResponse) WriteBytes

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

WriteBytes writes a byte[] slice that is valid Response

func (*ServerHTTPResponse) WriteJSON

func (res *ServerHTTPResponse) WriteJSON(
	statusCode int, headers Header, body interface{},
)

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 deprecated

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

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

Deprecated: Use EnsureContext instead

func (ServerTChannelHeader) EnsureContext

func (th ServerTChannelHeader) EnsureContext(ctx context.Context, keys []string, logger ContextLogger) error

EnsureContext 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.

func (ServerTChannelHeader) Unset

func (th ServerTChannelHeader) Unset(key string)

Unset unsets the value for a given header. Can be safely called multiple times

func (ServerTChannelHeader) Values

func (th ServerTChannelHeader) Values(key string) ([]string, bool)

Values retrieves the entire collection of values stored on a given header. Bool return value is used to distinguish between the presence of a header with golang's zerovalue slice and the absence of the header.

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 YAML(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 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 YAML 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) AsYaml

func (conf *StaticConfig) AsYaml() ([]byte, error)

AsYaml returns a YAML serialized version of the StaticConfig If the StaticConfig is destroyed or frozen, this method returns an error

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

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 YAML files. Set() will panic if the key exists or if frozen. Strongly recommended not to be used for production code.

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
	ContextLogger ContextLogger
	// contains filtered or unexported fields
}

TChannelClient implements TChannelCaller and makes outgoing Thrift calls.

func NewTChannelClient

func NewTChannelClient(
	ch *tchannel.Channel,
	contextLogger ContextLogger,
	scope tally.Scope,
	contextExtractor ContextExtractor,
	opt *TChannelClientOption,
) *TChannelClient

NewTChannelClient is deprecated, use NewTChannelClientContext instead

func NewTChannelClientContext

func NewTChannelClientContext(
	ch *tchannel.Channel,
	contextLogger ContextLogger,
	metrics ContextMetrics,
	contextExtractor ContextExtractor,
	opt *TChannelClientOption,
) *TChannelClient

NewTChannelClientContext 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.

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

	// Dynamically determine which alternate channel to call dynamically based on ruleEngine,
	// else fallback to default routing
	RuleEngine ruleengine.RuleEngine

	// list of headers which would be looked for matching a request with ruleEngine
	HeaderPatterns []string

	// the header key that is used together with the request uuid on context to
	// form a header when sending the request to downstream, e.g. "x-request-uuid"
	RequestUUIDHeaderKey string

	// AltChannelMap is a map for dynamic lookup of alternative channels
	AltChannelMap map[string]*tchannel.SubChannel

	// MaxAttempts is the maximum retry count for a client
	MaxAttempts int
}

TChannelClientOption is used when creating a new TChannelClient

type TChannelEndpoint

type TChannelEndpoint struct {
	TChannelHandler

	EndpointID string
	HandlerID  string
	Method     string
	// contains filtered or unexported fields
}

TChannelEndpoint wraps over a TChannelHandler and can be registered to a TChannelRouter to handle tchannel inbound call. It only has one Handle method which is delegated to the embedded TChannelHandler.

func NewTChannelEndpoint

func NewTChannelEndpoint(
	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(
	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) (ctxRes context.Context, 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 ThriftOutgoingEvent added in v2.0.4

type ThriftOutgoingEvent struct {
	MethodName  string
	ServiceName string

	ReqHeaders map[string]string
	ReqBody    []byte

	RspHeaders map[string]string
	RspBody    []byte
}

ThriftOutgoingEvent captures request and response data

func (*ThriftOutgoingEvent) Name added in v2.0.4

func (tce *ThriftOutgoingEvent) Name() string

type TimeoutAndRetryOptions

type TimeoutAndRetryOptions struct {
	OverallTimeoutInMs           time.Duration
	RequestTimeoutPerAttemptInMs time.Duration
	BackOffTimeAcrossRetriesInMs time.Duration
	MaxAttempts                  int
}

TimeoutAndRetryOptions specifies timeout and retries params for outbound calls

func BuildTimeoutAndRetryConfig

func BuildTimeoutAndRetryConfig(timeoutPerAttemptConf int, backOffTimeAcrossRetriesConf int,
	maxAttempts int, scaleFactor float64) *TimeoutAndRetryOptions

BuildTimeoutAndRetryConfig encapsulates timeout and retry configs in TimeoutAndRetryOptions struct

func GetTimeoutAndRetryOptions

func GetTimeoutAndRetryOptions(ctx context.Context) *TimeoutAndRetryOptions

GetTimeoutAndRetryOptions returns timeout and retry options stored in the context

type UnexpectedHTTPError

type UnexpectedHTTPError struct {
	StatusCode int
	RawBody    []byte
}

UnexpectedHTTPError defines an error for HTTP

func (*UnexpectedHTTPError) Error

func (rawErr *UnexpectedHTTPError) Error() string

Directories

Path Synopsis
Package plugins allows users to operate on statistics recorded for each circuit operation.
Package plugins allows users to operate on statistics recorded for each circuit operation.

Jump to

Keyboard shortcuts

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