Documentation ¶
Index ¶
- Constants
- func EnsureEmpty(r io.Reader, stage string) error
- func GetBuffer() *bytes.Buffer
- func GetDirnameFromRuntimeCaller(file string) string
- func GetEndpointRequestHeadersFromCtx(ctx context.Context) map[string]string
- func GetHostname() string
- func GetLogFieldsFromCtx(ctx context.Context) []zap.Field
- func GetRequestEndpointFromCtx(ctx context.Context) string
- func GetRoutingDelegateFromCtx(ctx context.Context) string
- func GetScopeTagsFromCtx(ctx context.Context) map[string]string
- func GetShardKeyFromCtx(ctx context.Context) string
- func LogErrorWarnTimeout(logger *zap.Logger, err error, msg string)deprecated
- func NewTChannelLogger(logger *zap.Logger) tchannel.Logger
- func NewTChannelStatsReporter(scope tally.Scope) tchannel.StatsReporter
- func ParamsFromContext(ctx context.Context) url.Values
- func PutBuffer(buf *bytes.Buffer)
- func ReadHeaders(r io.Reader) (map[string]string, error)
- func ReadStruct(reader io.Reader, s RWTStruct) error
- func RequestUUIDFromCtx(ctx context.Context) string
- func WithEndpointField(ctx context.Context, endpoint string) context.Context
- func WithEndpointRequestHeadersField(ctx context.Context, requestHeaders map[string]string) context.Context
- func WithLogFields(ctx context.Context, newFields ...zap.Field) context.Context
- func WithRoutingDelegate(ctx context.Context, rd string) context.Context
- func WithScopeTags(ctx context.Context, newFields map[string]string) context.Context
- func WithShardKey(ctx context.Context, sk string) context.Context
- func WriteHeaders(w io.Writer, headers map[string]string) error
- type ClientHTTPRequest
- func (req *ClientHTTPRequest) CheckHeaders(expected []string) error
- func (req *ClientHTTPRequest) Do() (*ClientHTTPResponse, error)
- func (req *ClientHTTPRequest) InjectSpanToHeader(span opentracing.Span, format interface{}) error
- func (req *ClientHTTPRequest) WriteBytes(method, url string, headers map[string]string, rawBody []byte) error
- func (req *ClientHTTPRequest) WriteJSON(method, url string, headers map[string]string, body interface{}) error
- type ClientHTTPResponse
- func (res *ClientHTTPResponse) CheckOKResponse(okResponses []int)
- func (res *ClientHTTPResponse) GetRawBody() []byte
- func (res *ClientHTTPResponse) ReadAll() ([]byte, error)
- func (res *ClientHTTPResponse) ReadAndUnmarshalBody(v interface{}) error
- func (res *ClientHTTPResponse) ReadAndUnmarshalBodyMultipleOptions(vs []interface{}) (interface{}, error)
- func (res *ClientHTTPResponse) UnmarshalBody(v interface{}, rawBody []byte) error
- type ConfigOption
- type ContextExtractor
- type ContextExtractors
- type ContextLogFieldsExtractor
- type ContextLogger
- type ContextMetrics
- type ContextScopeTagsExtractor
- type DefaultDependencies
- type GRPCClientCallHelper
- type GRPCClientOpts
- type Gateway
- func (gateway *Gateway) Bootstrap() error
- func (gateway *Gateway) Close()
- func (gateway *Gateway) InspectOrDie() map[string]interface{}
- func (gateway *Gateway) SetupClientTChannel(config *StaticConfig, serviceName string) *tchannel.Channel
- func (gateway *Gateway) Shutdown()
- func (gateway *Gateway) ShutdownTimeout() time.Duration
- func (gateway *Gateway) SubLogger(name string, level zapcore.Level) *zap.Logger
- func (gateway *Gateway) Wait()
- type HTTPClient
- type HTTPRouter
- type HTTPServer
- type HandlerFn
- type Header
- type Logger
- type MiddlewareHandle
- type MiddlewareStack
- type MiddlewareTchannelHandle
- type MiddlewareTchannelStack
- type Options
- type PostResponseCB
- type RWTStruct
- type RawTChannelClient
- type RouterEndpoint
- type RuntimeMetricsCollector
- type RuntimeMetricsOptions
- type ServerHTTPHeader
- func (zh ServerHTTPHeader) Add(key string, value string)
- func (zh ServerHTTPHeader) Ensure(keys []string, logger *zap.Logger) errordeprecated
- func (zh ServerHTTPHeader) EnsureContext(ctx context.Context, keys []string, logger ContextLogger) error
- func (zh ServerHTTPHeader) Get(key string) (string, bool)
- func (zh ServerHTTPHeader) GetAll(key string) []string
- func (zh ServerHTTPHeader) GetOrEmptyStr(key string) string
- func (zh ServerHTTPHeader) Keys() []string
- func (zh ServerHTTPHeader) Set(key string, value string)
- func (zh ServerHTTPHeader) Values(key string) ([]string, bool)
- type ServerHTTPRequest
- func (req *ServerHTTPRequest) CheckHeaders(headers []string) bool
- func (req *ServerHTTPRequest) CheckQueryValue(key string) bool
- func (req *ServerHTTPRequest) Context() context.Context
- func (req *ServerHTTPRequest) GetQueryBool(key string) (bool, bool)
- func (req *ServerHTTPRequest) GetQueryBoolList(key string) ([]bool, bool)
- func (req *ServerHTTPRequest) GetQueryFloat64(key string) (float64, bool)
- func (req *ServerHTTPRequest) GetQueryFloat64List(key string) ([]float64, bool)
- func (req *ServerHTTPRequest) GetQueryFloat64Set(key string) ([]float64, bool)
- func (req *ServerHTTPRequest) GetQueryInt16(key string) (int16, bool)
- func (req *ServerHTTPRequest) GetQueryInt16List(key string) ([]int16, bool)
- func (req *ServerHTTPRequest) GetQueryInt16Set(key string) ([]int16, bool)
- func (req *ServerHTTPRequest) GetQueryInt32(key string) (int32, bool)
- func (req *ServerHTTPRequest) GetQueryInt32List(key string) ([]int32, bool)
- func (req *ServerHTTPRequest) GetQueryInt32Set(key string) ([]int32, bool)
- func (req *ServerHTTPRequest) GetQueryInt64(key string) (int64, bool)
- func (req *ServerHTTPRequest) GetQueryInt64List(key string) ([]int64, bool)
- func (req *ServerHTTPRequest) GetQueryInt64Set(key string) ([]int64, bool)
- func (req *ServerHTTPRequest) GetQueryInt8(key string) (int8, bool)
- func (req *ServerHTTPRequest) GetQueryInt8List(key string) ([]int8, bool)
- func (req *ServerHTTPRequest) GetQueryInt8Set(key string) ([]int8, bool)
- func (req *ServerHTTPRequest) GetQueryValue(key string) (string, bool)
- func (req *ServerHTTPRequest) GetQueryValueList(key string) ([]string, bool)
- func (req *ServerHTTPRequest) GetQueryValueSet(key string) ([]string, bool)
- func (req *ServerHTTPRequest) GetQueryValues(key string) ([]string, bool)
- func (req *ServerHTTPRequest) GetRawBody() []byte
- func (req *ServerHTTPRequest) GetSpan() opentracing.Span
- func (req *ServerHTTPRequest) HasQueryPrefix(prefix string) bool
- func (req *ServerHTTPRequest) HasQueryValue(key string) bool
- func (req *ServerHTTPRequest) LogAndSendQueryError(err error, expected, key, value string)
- func (req *ServerHTTPRequest) PeekBody(keys ...string) ([]byte, jsonparser.ValueType, error)
- func (req *ServerHTTPRequest) ReadAll() ([]byte, bool)
- func (req *ServerHTTPRequest) ReadAndUnmarshalBody(body interface{}) bool
- func (req *ServerHTTPRequest) ReplaceBody(body []byte)
- func (req *ServerHTTPRequest) SetQueryValue(key string, value string)
- func (req *ServerHTTPRequest) StartTime() time.Time
- func (req *ServerHTTPRequest) UnmarshalBody(body interface{}, rawBody []byte) bool
- type ServerHTTPResponse
- func (res *ServerHTTPResponse) GetPendingResponse() ([]byte, int)
- func (res *ServerHTTPResponse) GetPendingResponseObject() interface{}
- func (res *ServerHTTPResponse) Headers() http.Header
- func (res *ServerHTTPResponse) MarshalResponseJSON(body interface{}) []byte
- func (res *ServerHTTPResponse) PeekBody(keys ...string) ([]byte, jsonparser.ValueType, error)
- func (res *ServerHTTPResponse) SendError(statusCode int, errMsg string, errCause error)
- func (res *ServerHTTPResponse) SendErrorString(statusCode int, errMsg string)
- func (res *ServerHTTPResponse) SendResponse(statusCode int, headers Header, body interface{}, bytes []byte)
- func (res *ServerHTTPResponse) WriteBytes(statusCode int, headers Header, bytes []byte)
- func (res *ServerHTTPResponse) WriteJSON(statusCode int, headers Header, body interface{})
- func (res *ServerHTTPResponse) WriteJSONBytes(statusCode int, headers Header, bytes []byte)
- type ServerTChannelHeader
- func (th ServerTChannelHeader) Add(key string, value string)
- func (th ServerTChannelHeader) Ensure(keys []string, logger *zap.Logger) errordeprecated
- func (th ServerTChannelHeader) EnsureContext(ctx context.Context, keys []string, logger ContextLogger) error
- func (th ServerTChannelHeader) Get(key string) (string, bool)
- func (th ServerTChannelHeader) Keys() []string
- func (th ServerTChannelHeader) Set(key string, value string)
- func (th ServerTChannelHeader) Values(key string) ([]string, bool)
- type SharedState
- type StaticConfig
- func (conf *StaticConfig) ContainsKey(key string) bool
- func (conf *StaticConfig) Destroy()
- func (conf *StaticConfig) Freeze()
- func (conf *StaticConfig) InspectOrDie() map[string]interface{}
- func (conf *StaticConfig) MustGetBoolean(key string) bool
- func (conf *StaticConfig) MustGetFloat(key string) float64
- func (conf *StaticConfig) MustGetInt(key string) int64
- func (conf *StaticConfig) MustGetString(key string) string
- func (conf *StaticConfig) MustGetStruct(key string, ptr interface{})
- func (conf *StaticConfig) SetConfigValueOrDie(key string, bytes []byte, dataType string)
- func (conf *StaticConfig) SetSeedOrDie(key string, value interface{})
- type TChannelCaller
- type TChannelClient
- type TChannelClientOption
- type TChannelEndpoint
- type TChannelHandler
- type TChannelLogger
- func (l TChannelLogger) Debug(msg string)
- func (l TChannelLogger) Debugf(msg string, args ...interface{})
- func (l TChannelLogger) Enabled(tlevel tchannel.LogLevel) bool
- func (l TChannelLogger) Error(msg string)
- func (l TChannelLogger) Fatal(msg string)
- func (l TChannelLogger) Fields() tchannel.LogFields
- func (l TChannelLogger) Info(msg string)
- func (l TChannelLogger) Infof(msg string, args ...interface{})
- func (l TChannelLogger) Warn(msg string)
- func (l TChannelLogger) WithFields(fields ...tchannel.LogField) tchannel.Logger
- type TChannelRouter
- type TchannelSharedState
- type UnexpectedHTTPError
Constants ¶
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" )
Variables ¶
This section is empty.
Functions ¶
func EnsureEmpty ¶
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 GetDirnameFromRuntimeCaller ¶
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 ¶ added in v0.2.0
GetEndpointRequestHeadersFromCtx returns the endpoint request headers, if it exists on context
func GetLogFieldsFromCtx ¶ added in v0.3.0
GetLogFieldsFromCtx returns the log fields attached to the context.Context
func GetRequestEndpointFromCtx ¶
GetRequestEndpointFromCtx returns the endpoint, if it exists on context
func GetRoutingDelegateFromCtx ¶
GetRoutingDelegateFromCtx returns the tchannel routing delegate info extracted from context.
func GetScopeTagsFromCtx ¶ added in v0.2.0
GetScopeTagsFromCtx returns the tag info extracted from context.
func GetShardKeyFromCtx ¶ added in v0.4.3
GetShardKeyFromCtx returns the tchannel shardkey info extracted from context.
func LogErrorWarnTimeout
deprecated
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 NewTChannelLogger ¶
NewTChannelLogger creates a TChannel logger given a zap logger
func NewTChannelStatsReporter ¶
NewTChannelStatsReporter returns a StatsReporter using the given tally.Scope.
func ParamsFromContext ¶ added in v0.2.0
ParamsFromContext extracts the URL parameters that are embedded in the context by the Zanzibar HTTP router implementation.
func ReadHeaders ¶
ReadHeaders reads key-value pairs encoded using WriteHeaders.
func ReadStruct ¶
ReadStruct reads the given Thriftrw struct.
func RequestUUIDFromCtx ¶ added in v0.3.0
RequestUUIDFromCtx returns the RequestUUID, if it exists on context
func WithEndpointField ¶
WithEndpointField adds the endpoint information in the request context.
func WithEndpointRequestHeadersField ¶ added in v0.2.0
func WithEndpointRequestHeadersField(ctx context.Context, requestHeaders map[string]string) context.Context
WithEndpointRequestHeadersField adds the endpoint request header information in the request context.
func WithLogFields ¶ added in v0.1.2
WithLogFields returns a new context with the given log fields attached to context.Context
func WithRoutingDelegate ¶
WithRoutingDelegate adds the tchannel routing delegate information in the request context.
func WithScopeTags ¶ added in v0.2.0
WithScopeTags returns a new context with the given scope tags attached to context.Context
func WithShardKey ¶ added in v0.4.3
WithShardKey adds the tchannel shard key information in the request context.
Types ¶
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 ¶
func (req *ClientHTTPRequest) Do() (*ClientHTTPResponse, error)
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 ¶ added in v0.6.0
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
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
func (*ClientHTTPResponse) ReadAndUnmarshalBodyMultipleOptions ¶ added in v0.3.0
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 ¶ added in v0.6.0
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 ¶ added in v0.2.0
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 ¶ added in v0.2.0
type ContextExtractors struct { ScopeTagsExtractors []ContextScopeTagsExtractor LogFieldsExtractors []ContextLogFieldsExtractor }
ContextExtractors warps extractors for context, implements ContextExtractor interface
func (*ContextExtractors) ExtractLogFields ¶ added in v0.2.0
func (c *ContextExtractors) ExtractLogFields(ctx context.Context) []zap.Field
ExtractLogFields extracts log fields from a context into a field.
func (*ContextExtractors) ExtractScopeTags ¶ added in v0.2.0
func (c *ContextExtractors) ExtractScopeTags(ctx context.Context) map[string]string
ExtractScopeTags extracts scope fields from a context into a tag.
type ContextLogFieldsExtractor ¶ added in v0.2.0
ContextLogFieldsExtractor defines func where extracts log fields from context
type ContextLogger ¶ added in v0.1.2
type ContextLogger interface { Debug(ctx context.Context, msg string, fields ...zap.Field) Error(ctx context.Context, msg string, fields ...zap.Field) Info(ctx context.Context, msg string, fields ...zap.Field) Panic(ctx context.Context, msg string, fields ...zap.Field) Warn(ctx context.Context, msg string, fields ...zap.Field) // DebugZ skips logs 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) ErrorZ(ctx context.Context, msg string, fields ...zap.Field) InfoZ(ctx context.Context, msg string, fields ...zap.Field) PanicZ(ctx context.Context, msg string, fields ...zap.Field) WarnZ(ctx context.Context, msg string, fields ...zap.Field) // 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.
func NewContextLogger ¶ added in v0.1.2
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 ¶ added in v0.2.0
type ContextMetrics interface { 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.
func NewContextMetrics ¶ added in v0.2.0
func NewContextMetrics(scope tally.Scope) ContextMetrics
NewContextMetrics create ContextMetrics to emit metrics with tags extracted from context.
type ContextScopeTagsExtractor ¶ added in v0.2.0
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 GRPCClientCallHelper ¶ added in v0.4.3
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 ¶ added in v0.4.3
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 ¶ added in v0.4.3
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 ¶ added in v0.4.3
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 // 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) Close ¶
func (gateway *Gateway) Close()
Close shuts down the servers and returns immediately
func (*Gateway) InspectOrDie ¶
InspectOrDie inspects the config for this gateway
func (*Gateway) SetupClientTChannel ¶ added in v1.0.0
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 ¶
ShutdownTimeout returns the shutdown configured timeout, which default to 10s.
type HTTPClient ¶
type HTTPClient struct { Client *http.Client BaseURL string DefaultHeaders map[string]string JSONWrapper jsonwrapper.JSONWrapper ContextLogger ContextLogger // 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 ¶ added in v0.2.0
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 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) 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 ¶
type HandlerFn func( context.Context, *ServerHTTPRequest, *ServerHTTPResponse, )
HandlerFn is a func that handles ServerHTTPRequest
type Header ¶
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) 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 ¶ added in v0.2.0
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, ) 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 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 ¶
func (m *MiddlewareStack) Handle( ctx context.Context, req *ServerHTTPRequest, res *ServerHTTPResponse)
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 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) (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 // 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 ¶
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 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.
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 ¶
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) EnsureContext ¶ added in v0.2.0
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) Values ¶ added in v0.6.4
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 ¶ added in v0.2.0
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 ¶ added in v0.3.0
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 ¶ added in v0.3.0
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 ¶ added in v0.3.0
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 ¶ added in v0.3.0
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 ¶ added in v0.3.0
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 ¶ added in v0.3.0
func (req *ServerHTTPRequest) GetQueryValueList(key string) ([]string, bool)
GetQueryValueList will return all query parameters for key.
func (*ServerHTTPRequest) GetQueryValueSet ¶ added in v0.3.0
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 ¶ added in v0.4.3
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 ¶ added in v0.3.0
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 ¶ added in v0.3.0
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 ¶ added in v0.4.3
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 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 ¶ added in v0.6.7
func (res *ServerHTTPResponse) GetPendingResponseObject() interface{}
GetPendingResponseObject lets you read the pending body object which isn't sent back yet.
func (*ServerHTTPResponse) Headers ¶ added in v0.3.0
func (res *ServerHTTPResponse) Headers() http.Header
Headers returns the underlying http response's headers
func (*ServerHTTPResponse) MarshalResponseJSON ¶ added in v0.6.0
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 ¶ added in v0.6.0
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 ¶ added in v0.3.0
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 ¶
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) EnsureContext ¶ added in v0.2.0
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) Values ¶ added in v0.6.4
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) 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 ¶ added in v0.2.0
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.
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 }
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) (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 ¶
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 ¶
UnexpectedHTTPError defines an error for HTTP
func (*UnexpectedHTTPError) Error ¶
func (rawErr *UnexpectedHTTPError) Error() string
Source Files ¶
- client_http_request.go
- client_http_response.go
- constants.go
- context.go
- gateway.go
- grpc_client.go
- http_client.go
- http_server.go
- middlewares.go
- middlewares_tchannel.go
- router.go
- runtime_metrics.go
- server_header.go
- server_http_request.go
- server_http_response.go
- static_config.go
- tchannel_client.go
- tchannel_client_raw.go
- tchannel_headers.go
- tchannel_helpers.go
- tchannel_inbound_call.go
- tchannel_interfaces.go
- tchannel_logger.go
- tchannel_metrics.go
- tchannel_outbound_call.go
- tchannel_server.go
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. |