hrpc

package module
v0.0.0-...-ee3e755 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2022 License: MIT Imports: 32 Imported by: 1

README

Requirements:

go : minimum version 1.13

Install

go get github.com/kamva/hexa-rpc

Proposal

  • Change Hexa error status from http status to gRPC status, because:

    Advantages

    • If we using gRPC status, so will dont need to convert https status to gRPC status, we will just convert our gRPC status to http on the gateway responses.

    Drawbacks

    • If we use gRPC codes, so we will need to import gRPC library in all of libraries that need to define or use hexa error, while http statues exists in most languages as standard libraries.

Todo

  • Use recover interceptor in the gRPC interceptors.
  • Implement status to Hexa error (and reverse) mapper.
  • Set Hexa logger as gRPC Logger (implement gRPC logger adapter by hexa logger)
  • Implement request logger (log start-time, end-time, method, error,...)
  • We should implement all of our interceptors for the Stream request/responses also (for now we just support Unary Request/responses).
  • Write Tests
  • Add badges to README.
  • CI

Documentation

Index

Constants

View Source
const (
	// ContextKeyHexaKeys is the key we use in grpc context to keep hexa keys list on export and import.
	ContextKeyHexaKeys = "_hexa_ctx_keys"
)

Variables

View Source
var (
	ErrUnknownError = hexa.NewError(http.StatusInternalServerError, "lib.hrpc.unknown_error")
)
View Source
var File_hrpc_error_proto protoreflect.FileDescriptor

Functions

func BoolVal

func BoolVal(v *bool) *wrapperspb.BoolValue

func CodeFromHTTPStatus

func CodeFromHTTPStatus(status int) codes.Code

CodeFromHTTPStatus converts a https status into corresponding gRPC error code. Note: error mapping from http status to hRPC code is not good, do not use this function as you can.

func DoubleVal

func DoubleVal(v *float64) *wrapperspb.DoubleValue

func DurationToTimeMillisFormatter

func DurationToTimeMillisFormatter(duration time.Duration) hexa.Map

DurationToTimeMillisFormatter converts the duration to milliseconds.

func Error

func Error(status *status.Status) hexa.Error

Error gets a gRPC status and converts it to Hexa error

func FloatVal

func FloatVal(v *float32) *wrapperspb.FloatValue

func HTTPStatusFromCode

func HTTPStatusFromCode(code codes.Code) int

HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto Note: We got this function from the [gRPC gateway](https://github.com/grpc-ecosystem/grpc-gateway/blob/master/runtime/errors.go)

func HexaErrFromErr

func HexaErrFromErr(err error) hexa.Error

HexaErrFromErr returns hexa error from raw error.

func Int32Val

func Int32Val(v *int32) *wrapperspb.Int32Value

func Int32ValFromInt

func Int32ValFromInt(v *int) *wrapperspb.Int32Value

func Int64Val

func Int64Val(v *int64) *wrapperspb.Int64Value

func MaskMapPaths

func MaskMapPaths(m hexa.Map, mask *field_mask.FieldMask, depth int)

MaskMapPaths mask all paths in the provided map with the provided depth.

func NewGRPCHealth

func NewGRPCHealth(id string, addr string) hexa.Health

func NewHealthServer

func NewHealthServer() grpc_health_v1.HealthServer

func NewHexaErrFromErrorDetails

func NewHexaErrFromErrorDetails(details *ErrorDetails) hexa.Error

func NewHexaService

func NewHexaService(h hexa.Health, l net.Listener, s *grpc.Server) hexa.Service

func NewLogger

func NewLogger(l hlog.Logger, verbosity int) grpclog.LoggerV2

NewLogger returns new instance of the gRPC Logger v2

func ParseFullMethod

func ParseFullMethod(fullMethod string) (string, []attribute.KeyValue)

ParseFullMethod returns a span name following the OpenTelemetry semantic conventions as well as all applicable span attribute.KeyValue attributes based on a gRPC's FullMethod. [got from here](https://github.com/open-telemetry/opentelemetry-go-contrib/blob/main/instrumentation/google.golang.org/grpc/otelgrpc/internal/parse.go)

func RecoverHandler

func RecoverHandler(r interface{}) error

RecoverHandler handle handle recovered data from panics in the gRPC server

func Status

func Status(hexaErr hexa.Error, t hexa.Translator) *status.Status

Status gets a Hexa error and converts it to gRPC Status Implementation Details: - Convert http status to gRPC code - Set localized message and data.

func StringVal

func StringVal(v *string) *wrapperspb.StringValue

func TimestampVal

func TimestampVal(t *time.Time) *timestamppb.Timestamp

Types

type DurationFormatter

type DurationFormatter func(duration time.Duration) hexa.Map

DurationFormatter get a duration and return formatted duration as key (name of field that should log) and value(formatted time)

type ErrInterceptorOptions

type ErrInterceptorOptions struct {
	Logger       hlog.Logger
	Translator   hexa.Translator
	ReportErrors bool // report errors ?
}

ErrInterceptorOptions is the options

type ErrorDetails

type ErrorDetails struct {

	// HTTP status
	Status int32 `protobuf:"varint,1,opt,name=status,proto3" json:"status,omitempty"`
	// Error id
	Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`
	// Localized error message
	LocalizedMessage string `protobuf:"bytes,3,opt,name=localized_message,json=localizedMessage,proto3" json:"localized_message,omitempty"`
	// json marshalled error data
	Data string `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"`
	// contains filtered or unexported fields
}

--------------------------------

Hexa error message

-------------------------------- Go Generation command: protoc --go_out=./ --go_opt="module=github.com/kamva/hrpc hrpc_error.proto

func NewErrorDetails

func NewErrorDetails(t hexa.Translator, hexaErr hexa.Error) *ErrorDetails

func NewErrorDetailsFromRawError

func NewErrorDetailsFromRawError(ctx context.Context, err error) *ErrorDetails

func (*ErrorDetails) Descriptor deprecated

func (*ErrorDetails) Descriptor() ([]byte, []int)

Deprecated: Use ErrorDetails.ProtoReflect.Descriptor instead.

func (*ErrorDetails) GetData

func (x *ErrorDetails) GetData() string

func (*ErrorDetails) GetId

func (x *ErrorDetails) GetId() string

func (*ErrorDetails) GetLocalizedMessage

func (x *ErrorDetails) GetLocalizedMessage() string

func (*ErrorDetails) GetStatus

func (x *ErrorDetails) GetStatus() int32

func (*ErrorDetails) ProtoMessage

func (*ErrorDetails) ProtoMessage()

func (*ErrorDetails) ProtoReflect

func (x *ErrorDetails) ProtoReflect() protoreflect.Message

func (*ErrorDetails) Reset

func (x *ErrorDetails) Reset()

func (*ErrorDetails) String

func (x *ErrorDetails) String() string

type ErrorInterceptor

type ErrorInterceptor struct{}

ErrorInterceptor implements a gRPC interceptor to convert error into status and reverse.

func NewErrorInterceptor

func NewErrorInterceptor() *ErrorInterceptor

NewErrorInterceptor returns new instance of the ErrorInterceptor

func (ErrorInterceptor) UnaryClientInterceptor

func (i ErrorInterceptor) UnaryClientInterceptor() grpc.UnaryClientInterceptor

UnaryClientInterceptor returns client interceptor to convert status to Hexa error. Note: error interceptor must be first client interceptor.

func (ErrorInterceptor) UnaryServerInterceptor

UnaryServerInterceptor returns unary server interceptor to convert Hexa error to status.

type HexaContextInterceptor

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

HexaContextInterceptor is the gRPC interceptor to pass hexa context through gRPC. Note: we do not provide stream interceptors, if you think need it, create PR or issue.

func NewHexaContextInterceptor

func NewHexaContextInterceptor(p hexa.ContextPropagator) *HexaContextInterceptor

NewHexaContextInterceptor returns new instance of the HexaContextInterceptor.

func (*HexaContextInterceptor) UnaryClientInterceptor

func (ci *HexaContextInterceptor) UnaryClientInterceptor(ctx context.Context, method string, req interface{}, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error

func (*HexaContextInterceptor) UnaryServerInterceptor

func (ci *HexaContextInterceptor) UnaryServerInterceptor(c context.Context, req interface{}, info *grpc.UnaryServerInfo, h grpc.UnaryHandler) (interface{}, error)

type HexaService

type HexaService struct {
	hexa.Health // Embed to include health check too.
	net.Listener
	*grpc.Server
}

HexaService implements hexa service.

func (*HexaService) Run

func (s *HexaService) Run() (<-chan error, error)

func (*HexaService) Shutdown

func (s *HexaService) Shutdown(ctx context.Context) error

type LoggerOptions

type LoggerOptions struct {
	ErrorToCode       grpc_logging.ErrorToCode
	ShouldLog         grpc_logging.Decider
	DurationFormatter DurationFormatter
	LogRequest        bool
	LogResponse       bool
}

func DefaultLoggerOptions

func DefaultLoggerOptions(logRequestResponse bool) LoggerOptions

type Metrics

type Metrics struct{}

func (*Metrics) UnaryServerInterceptor

func (m *Metrics) UnaryServerInterceptor(opts MetricsOptions) grpc.UnaryServerInterceptor

type MetricsOptions

type MetricsOptions struct {
	MeterProvider metric.MeterProvider
	ServerName    string
}

type RequestLogger

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

RequestLogger implements gRPC interceptor to log each request

func NewRequestLogger

func NewRequestLogger(l hlog.Logger) *RequestLogger

NewRequestLogger returns new instance of the RequestLogger

func (*RequestLogger) UnaryServerInterceptor

func (l *RequestLogger) UnaryServerInterceptor(o LoggerOptions) grpc.UnaryServerInterceptor

Jump to

Keyboard shortcuts

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