MSP-8974 fix tests
This commit is contained in:
1 parent
71498785ea
commit
fa8bc6c1b7
50 files changed
+392
-2975
No files matched your search
-112
@@ -1,112 +0,0 @@
|
||||
# Package `client`
|
||||
|
||||
Пакет `client` предоставляет гибкий gRPC-клиент с поддержкой балансировки нагрузки, middleware для логирования, метрик,
|
||||
трассировки и динамическим обновлением списка хостов.
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Основная структура клиента для взаимодействия с gRPC-серверами. Поддерживает балансировку нагрузки, цепочки middleware и
|
||||
динамическое обновление списка хостов.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New(initialHosts []string, opts ...Option) (*Client, error)`
|
||||
|
||||
Создать новый клиент с указанными начальными хостами и опциями:
|
||||
|
||||
- `WithMiddlewares(middlewares ...request.Middleware) Option` – добавить middleware в цепочку обработки запроса.
|
||||
- `WithDialOptions(dialOptions ...grpc.DialOption) Option` – опция для передачи параметров подключения gRPC (например,
|
||||
TLS, таймауты)
|
||||
- `WithCodec(codec Codec) Option` – переопределяет codec для кодирования/декодирования, по умолчанию `zstd`
|
||||
- `WithEncodeThreshold(threshold int) Option` – переопределяет значение выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest), по умолчанию 128 КБ (параметр в байтах).
|
||||
- `WithEncodeRequest(encode bool) Option` – переопределить флаг кодирования запроса. Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен `x-content-encoding` со значением типа codec и тело запроса будет закодировано, по умолчанию false.
|
||||
- `WithAcceptEncodedResponse(accept bool) Option` – переопределить флаг флаг приёма закодированных ответов. Если включен, то в заголовки запроса будет добавлен `x-accept-encoding` со значением типа codec + identity (пример `zstd, identity`), по умолчанию true.
|
||||
|
||||
#### `(cli *Client) Invoke(endpoint string) *request.Builder`
|
||||
|
||||
Инициирует запрос к указанному эндпоинту. Возвращает билдер для выполнения запроса.
|
||||
|
||||
#### `(cli *Client) Upgrade(hosts []string)`
|
||||
|
||||
Атомарно обновить список хостов.
|
||||
|
||||
#### `(cli *Client) Close() error`
|
||||
|
||||
Закрыть соединение с сервером.
|
||||
|
||||
#### `(cli *Client) BackendClient() isp.BackendServiceClient`
|
||||
|
||||
Получить низкоуровневый клиент для прямого взаимодействия с gRPC-сервисом.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `Default(restMiddlewares ...request.Middleware) (*Client, error)`
|
||||
|
||||
Создать клиент с настройками по умолчанию:
|
||||
|
||||
- Максимальный размер сообщения 64 МБ.
|
||||
- Middleware для генерации requestId, сбора метрик через `grpc_metrics.ClientStorage` и трейсинга
|
||||
|
||||
#### `RequestId() request.Middleware`
|
||||
|
||||
Middleware для автоматической генерации requestId для передачи в заголовках. Если в контексте будет указан requestId, то
|
||||
передаваться будет именно он.
|
||||
|
||||
#### `Log(logger log.Logger, logBody bool) request.Middleware`
|
||||
|
||||
Middleware для логирования запросов и ответов. Логирует тело запроса/ответа, если `logBody = true`.
|
||||
|
||||
#### `Metrics(storage MetricStorage) request.Middleware`
|
||||
|
||||
Middleware для сбора метрик длительности запросов.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
cli, err := client.Default(client.Log(logger, true))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer cli.Close()
|
||||
|
||||
cli.Upgrade([]string{"host1:8080", "host2:9000"})
|
||||
|
||||
users := make([]user, 0)
|
||||
err = cli.Invoke("/get_users").
|
||||
JsonResponseBody(&users).
|
||||
Do(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for _, u := range users {
|
||||
/* handle each user */
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
-210
@@ -1,210 +0,0 @@
|
||||
// Package client provides a gRPC client implementation with built-in load balancing,
|
||||
// middleware support, and observability features.
|
||||
//
|
||||
// The client supports dynamic host updates for service discovery and integrates with
|
||||
// the ISP kit framework's logging, metrics, and tracing systems.
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
grpc2 "github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/resolver"
|
||||
"google.golang.org/grpc/resolver/manual"
|
||||
)
|
||||
|
||||
const (
|
||||
// resolverScheme defines the custom resolver scheme for host discovery.
|
||||
resolverScheme = "isp"
|
||||
// resolverUrl is the target URL for the manual resolver.
|
||||
resolverUrl = resolverScheme + ":///"
|
||||
|
||||
defaultEncodeThreshold = codec.DefaultEncodeThreshold
|
||||
)
|
||||
|
||||
type Codec interface {
|
||||
Type() string
|
||||
EncodeBytes(b []byte) ([]byte, error)
|
||||
DecodeBytes(b []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// Client is a gRPC client with support for middleware, load balancing, and dynamic host updates.
|
||||
// It provides a fluent API for building requests and automatically handles connection management.
|
||||
// Client is safe for concurrent use by multiple goroutines.
|
||||
type Client struct {
|
||||
middlewares []request.Middleware
|
||||
dialOptions []grpc.DialOption
|
||||
|
||||
roundTripper request.RoundTripper
|
||||
hostsResolver *manual.Resolver
|
||||
grpcCli *grpc.ClientConn
|
||||
backendCli isp.BackendServiceClient
|
||||
|
||||
currentHosts atomic.Value
|
||||
|
||||
codec Codec
|
||||
encodeThreshold int
|
||||
acceptEncodedResponse bool
|
||||
encodeRequest bool
|
||||
}
|
||||
|
||||
// New creates a new Client with the specified initial hosts and options.
|
||||
// Returns an error if the gRPC client cannot be initialized.
|
||||
// The client automatically connects to the provided hosts and applies all configured middleware.
|
||||
func New(initialHosts []string, opts ...Option) (*Client, error) {
|
||||
cli := &Client{
|
||||
codec: codec.Default,
|
||||
acceptEncodedResponse: true,
|
||||
encodeRequest: false,
|
||||
encodeThreshold: defaultEncodeThreshold,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cli)
|
||||
}
|
||||
|
||||
hostsResolver := manual.NewBuilderWithScheme(resolverScheme)
|
||||
hostsResolver.InitialState(resolver.State{
|
||||
Addresses: toAddresses(initialHosts),
|
||||
})
|
||||
dialOptions := cli.dialOptions
|
||||
dialOptions = append(
|
||||
dialOptions,
|
||||
grpc.WithResolvers(hostsResolver),
|
||||
grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
|
||||
)
|
||||
|
||||
grpcCli, err := grpc.NewClient(resolverUrl, dialOptions...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "new grpc client")
|
||||
}
|
||||
grpcCli.Connect()
|
||||
backendCli := isp.NewBackendServiceClient(grpcCli)
|
||||
|
||||
cli.currentHosts = atomic.Value{}
|
||||
cli.currentHosts.Store(initialHosts)
|
||||
cli.hostsResolver = hostsResolver
|
||||
cli.backendCli = backendCli
|
||||
cli.grpcCli = grpcCli
|
||||
|
||||
roundTripper := cli.do
|
||||
for _, v := range slices.Backward(cli.middlewares) {
|
||||
roundTripper = v(roundTripper)
|
||||
}
|
||||
cli.roundTripper = roundTripper
|
||||
|
||||
return cli, nil
|
||||
}
|
||||
|
||||
// Invoke creates a request builder for the specified endpoint.
|
||||
// The builder provides a fluent API for configuring and executing the request.
|
||||
func (cli *Client) Invoke(endpoint string) *request.Builder {
|
||||
return request.NewBuilder(
|
||||
cli.roundTripper,
|
||||
endpoint,
|
||||
request.EncodeSettings{
|
||||
EncodeRequest: cli.encodeRequest,
|
||||
EncodeThreshold: cli.encodeThreshold,
|
||||
AcceptEncodedResponse: cli.acceptEncodedResponse,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Upgrade updates the list of backend hosts for load balancing.
|
||||
// This enables dynamic service discovery without restarting the client.
|
||||
// Thread-safe for concurrent use.
|
||||
func (cli *Client) Upgrade(hosts []string) {
|
||||
cli.currentHosts.Store(hosts)
|
||||
cli.hostsResolver.UpdateState(resolver.State{
|
||||
Addresses: toAddresses(hosts),
|
||||
})
|
||||
}
|
||||
|
||||
// Close closes the gRPC client connection.
|
||||
// Should be called when the client is no longer needed.
|
||||
func (cli *Client) Close() error {
|
||||
return cli.grpcCli.Close()
|
||||
}
|
||||
|
||||
// BackendClient returns the underlying gRPC BackendServiceClient.
|
||||
// Useful for direct gRPC calls bypassing the client abstraction.
|
||||
func (cli *Client) BackendClient() isp.BackendServiceClient {
|
||||
return cli.backendCli
|
||||
}
|
||||
|
||||
// do executes the actual gRPC request through the middleware chain.
|
||||
// Returns an error if the client is not properly initialized or the request fails.
|
||||
func (cli *Client) do(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
currentHosts := cli.currentHosts.Load().([]string) // nolint:forcetypeassert
|
||||
if len(currentHosts) == 0 {
|
||||
return nil, errors.New("grpc client: client is not initialized properly: empty hosts array")
|
||||
}
|
||||
|
||||
encodeSettings := builder.EncodeSettings
|
||||
if encodeSettings.AcceptEncodedResponse {
|
||||
ctx = metadata.AppendToOutgoingContext(ctx,
|
||||
grpc2.AcceptEncodingHeader,
|
||||
strings.Join([]string{cli.codec.Type(), "identity"}, ", "),
|
||||
)
|
||||
}
|
||||
|
||||
requestBody := message.GetBytesBody()
|
||||
if encodeSettings.EncodeRequest && len(requestBody) > encodeSettings.EncodeThreshold {
|
||||
ctx = metadata.AppendToOutgoingContext(ctx,
|
||||
grpc2.ContentEncodingHeader,
|
||||
cli.codec.Type(),
|
||||
)
|
||||
requestBody, err := cli.codec.EncodeBytes(requestBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
message.Body = &isp.Message_BytesBody{
|
||||
BytesBody: requestBody,
|
||||
}
|
||||
}
|
||||
|
||||
var header metadata.MD
|
||||
resp, err := cli.backendCli.Request(
|
||||
ctx,
|
||||
message,
|
||||
grpc.Header(&header),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
contentEncoding, _ := grpc2.StringFromMd(grpc2.ContentEncodingHeader, header)
|
||||
if contentEncoding != cli.codec.Type() {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
decoded, err := cli.codec.DecodeBytes(resp.GetBytesBody())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &isp.Message_BytesBody{
|
||||
BytesBody: decoded,
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// toAddresses converts a slice of host strings to gRPC resolver addresses.
|
||||
func toAddresses(hosts []string) []resolver.Address {
|
||||
addresses := make([]resolver.Address, len(hosts))
|
||||
for i, host := range hosts {
|
||||
addresses[i] = resolver.Address{
|
||||
Addr: host,
|
||||
}
|
||||
}
|
||||
return addresses
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
ispgrpc "github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/grpc_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// Default creates a Client with pre-configured middleware for observability.
|
||||
// Includes request ID propagation, metrics collection, and distributed tracing.
|
||||
// Uses insecure transport by default (suitable for development and testing).
|
||||
// Accepts additional middleware to be appended after the default ones.
|
||||
// Returns an error if the client cannot be initialized.
|
||||
func Default(restMiddlewares ...request.Middleware) (*Client, error) {
|
||||
middlewares := append(
|
||||
[]request.Middleware{
|
||||
RequestId(),
|
||||
Metrics(grpc_metrics.NewClientStorage(metrics.DefaultRegistry)),
|
||||
client_tracing.NewConfig().Middleware(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
return New(
|
||||
nil,
|
||||
WithDialOptions(
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithDefaultCallOptions(
|
||||
grpc.WaitForReady(true),
|
||||
grpc.MaxCallSendMsgSize(ispgrpc.DefaultMaxSizeByte),
|
||||
grpc.MaxCallRecvMsgSize(ispgrpc.DefaultMaxSizeByte),
|
||||
),
|
||||
),
|
||||
WithMiddlewares(middlewares...),
|
||||
)
|
||||
}
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// logConfig holds logging configuration for client middleware.
|
||||
type logConfig struct {
|
||||
logRequestBody bool
|
||||
logResponseBody bool
|
||||
combinedLog bool
|
||||
}
|
||||
|
||||
// RequestId is a middleware that propagates request IDs across service boundaries.
|
||||
// If no request ID is present in the context, it generates a new one.
|
||||
// The request ID is added to outgoing metadata for tracing purposes.
|
||||
func RequestId() request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
requestId := requestid.FromContext(ctx)
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
}
|
||||
|
||||
ctx = metadata.AppendToOutgoingContext(ctx, requestid.Header, requestId)
|
||||
return next(ctx, builder, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Log creates a middleware that logs gRPC client requests and responses.
|
||||
// When logBody is true, request and response bodies are included in the logs.
|
||||
// Logs at Debug level for requests and responses.
|
||||
func Log(logger log.Logger, logBody bool) request.Middleware {
|
||||
cfg := &logConfig{
|
||||
logRequestBody: logBody,
|
||||
logResponseBody: logBody,
|
||||
}
|
||||
return logMiddleware(logger, cfg)
|
||||
}
|
||||
|
||||
// LogWithOptions creates a middleware that logs gRPC client requests and responses with custom options.
|
||||
// Provides fine-grained control over what is logged (request body, response body, combined logs).
|
||||
func LogWithOptions(logger log.Logger, opts ...LogOption) request.Middleware {
|
||||
cfg := &logConfig{
|
||||
logRequestBody: false,
|
||||
logResponseBody: false,
|
||||
combinedLog: false,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
}
|
||||
|
||||
if cfg.combinedLog {
|
||||
return logCombinedMiddleware(logger, cfg)
|
||||
}
|
||||
return logMiddleware(logger, cfg)
|
||||
}
|
||||
|
||||
// logMiddleware implements request/response logging with separate log entries.
|
||||
func logMiddleware(logger log.Logger, cfg *logConfig) request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
requestFields := []log.Field{
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
}
|
||||
if cfg.logRequestBody {
|
||||
requestFields = append(requestFields, log.ByteString("requestBody", message.GetBytesBody()))
|
||||
}
|
||||
logger.Debug(ctx, "grpc client: request", requestFields...)
|
||||
|
||||
var responseFields []log.Field
|
||||
|
||||
now := time.Now()
|
||||
resp, err := next(ctx, builder, message)
|
||||
if err != nil {
|
||||
responseFields = append(responseFields,
|
||||
log.Any("error", err),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
logger.Debug(ctx, "grpc client: response with error", responseFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
responseFields = append(responseFields,
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
if cfg.logResponseBody {
|
||||
responseFields = append(responseFields, log.ByteString("responseBody", resp.GetBytesBody()))
|
||||
}
|
||||
|
||||
logger.Debug(ctx, "grpc client: response", responseFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// logCombinedMiddleware implements logging with a single combined log entry.
|
||||
func logCombinedMiddleware(logger log.Logger, cfg *logConfig) request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
logFields := []log.Field{
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
}
|
||||
if cfg.logRequestBody {
|
||||
logFields = append(logFields, log.ByteString("requestBody", message.GetBytesBody()))
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
resp, err := next(ctx, builder, message)
|
||||
|
||||
logFields = append(logFields,
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logFields = append(logFields, log.Any("error", err))
|
||||
logger.Debug(ctx, "grpc client: log with error", logFields...)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if cfg.logResponseBody {
|
||||
logFields = append(logFields, log.ByteString("responseBody", resp.GetBytesBody()))
|
||||
}
|
||||
logger.Debug(ctx, "grpc client: log", logFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MetricStorage defines the interface for metric storage implementations.
|
||||
// Used by the Metrics middleware to collect timing information.
|
||||
type MetricStorage interface {
|
||||
// ObserveDuration records the duration of a request for the given endpoint.
|
||||
ObserveDuration(endpoint string, duration time.Duration)
|
||||
}
|
||||
|
||||
// Metrics creates a middleware that collects timing metrics for gRPC client requests.
|
||||
// The storage implementation receives the endpoint name and request duration.
|
||||
func Metrics(storage MetricStorage) request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
start := time.Now()
|
||||
response, err := next(ctx, builder, message)
|
||||
storage.ObserveDuration(builder.Endpoint, time.Since(start))
|
||||
return response, err
|
||||
}
|
||||
}
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// Option configures a Client using the functional options pattern.
|
||||
type Option func(cli *Client)
|
||||
|
||||
// WithMiddlewares adds one or more request middleware to the client.
|
||||
// Middleware are executed in the order they are provided.
|
||||
func WithMiddlewares(middlewares ...request.Middleware) Option {
|
||||
return func(cli *Client) {
|
||||
cli.middlewares = append(cli.middlewares, middlewares...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithDialOptions sets custom gRPC dial options for the client.
|
||||
// Note: This replaces any previously set dial options.
|
||||
func WithDialOptions(dialOptions ...grpc.DialOption) Option {
|
||||
return func(cli *Client) {
|
||||
cli.dialOptions = dialOptions
|
||||
}
|
||||
}
|
||||
|
||||
// WithAcceptEncodedResponse sets acceptEncodedResponse flag.
|
||||
func WithAcceptEncodedResponse(accept bool) Option {
|
||||
return func(c *Client) {
|
||||
c.acceptEncodedResponse = accept
|
||||
}
|
||||
}
|
||||
|
||||
// WithEncodeRequest sets encodeRequest flag.
|
||||
func WithEncodeRequest(encode bool) Option {
|
||||
return func(c *Client) {
|
||||
c.encodeRequest = encode
|
||||
}
|
||||
}
|
||||
|
||||
// WithEncodeThreshold sets the request encoding threshold in bytes.
|
||||
func WithEncodeThreshold(thresholdBytes int) Option {
|
||||
return func(c *Client) {
|
||||
c.encodeThreshold = thresholdBytes
|
||||
}
|
||||
}
|
||||
|
||||
// WithCodec sets codec.
|
||||
func WithCodec(codec Codec) Option {
|
||||
return func(c *Client) {
|
||||
c.codec = codec
|
||||
}
|
||||
}
|
||||
|
||||
// LogOption configures logging behavior for request middleware.
|
||||
type LogOption func(cfg *logConfig)
|
||||
|
||||
// WithLogBody enables logging of both request and response bodies.
|
||||
func WithLogBody(logBody bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logResponseBody = logBody
|
||||
cfg.logRequestBody = logBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithLogResponseBody enables or disables logging of response bodies.
|
||||
func WithLogResponseBody(logResponseBody bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logResponseBody = logResponseBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithLogRequestBody enables or disables logging of request bodies.
|
||||
func WithLogRequestBody(logRequestBody bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logRequestBody = logRequestBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithCombinedLog enables a single combined log entry for request and response.
|
||||
// When disabled, requests and responses are logged separately.
|
||||
func WithCombinedLog(enable bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.combinedLog = enable
|
||||
}
|
||||
}
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
# Package `request`
|
||||
|
||||
Пакет `request` предоставляет билдер для построения gRPC-запросов с поддержкой JSON-сериализации, таймаутов, метаданных
|
||||
и цепочек обработки через middleware. Интегрируется с клиентом из пакета [`client`](../client.go).
|
||||
|
||||
## Types
|
||||
|
||||
### Builder
|
||||
|
||||
Структура для пошагового конструирования gRPC-запроса. Обрабатывает сериализацию/десериализацию JSON, управление
|
||||
контекстом и метаданными.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewBuilder(roundTripper RoundTripper, endpoint string) *Builder`
|
||||
|
||||
Создать новый билдер для указанного эндпоинта.
|
||||
|
||||
#### `(req *Builder) ApplicationId(appId int) *Builder`
|
||||
|
||||
Установить идентификатор системы в заголовок `x-application-identity`.
|
||||
|
||||
#### `(req *Builder) JsonRequestBody(reqBody any) *Builder`
|
||||
|
||||
Задать тело запроса в формате JSON. Объект будет сериализован автоматически при помощи функций из пакета [
|
||||
`json`](../../json) (маршалинг без тэгов в camelCase).
|
||||
|
||||
#### `(req *Builder) JsonResponseBody(respPtr any) *Builder`
|
||||
|
||||
Задать указатель для десериализации тела ответа из JSON.
|
||||
|
||||
#### `(req *Builder) Timeout(timeout time.Duration) *Builder`
|
||||
|
||||
Установить тайм-аут для запроса. По умолчанию: 15 секунд.
|
||||
|
||||
#### `(req *Builder) AppendMetadata(k string, v ...string) *Builder`
|
||||
|
||||
Добавить кастомные метаданные в запрос.
|
||||
|
||||
#### `(b *RequestBuilder) EncodeRequest(encode bool) *RequestBuilder`
|
||||
|
||||
Установить флаг кодирования запроса.
|
||||
Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен `content-encoding` со значением типа codec и тело запроса будет закодировано.
|
||||
|
||||
#### `(b *RequestBuilder) EncodeThreshold(threshold int) *RequestBuilder`
|
||||
|
||||
Установить threshold в байтах, выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest).
|
||||
|
||||
#### `(b *RequestBuilder) AcceptEncodedResponse(accept bool) *RequestBuilder`
|
||||
|
||||
Установить флаг приёма закодированных ответов.
|
||||
Если включен, то в заголовки запроса будет добавлен `accept-encoding` со значением типа codec + identity (пример `zstd, identity`).
|
||||
|
||||
#### `(req *Builder) Do(ctx context.Context) error`
|
||||
|
||||
Выполнить запрос. Автоматически:
|
||||
|
||||
1. Сериализует тело запроса в JSON
|
||||
2. Добавляет системные заголовки (`x-application-identity`, `proxy_method_name`)
|
||||
3. Обрабатывает цепочку middleware
|
||||
4. Десериализует ответ (если задан `responsePtr`)
|
||||
|
||||
## Functions
|
||||
|
||||
#### `Default(restMiddlewares ...request.Middleware) (*Client, error)`
|
||||
|
||||
Создать клиент с настройками по умолчанию:
|
||||
|
||||
- Максимальный размер сообщения 64 МБ.
|
||||
- Middleware для генерации requestId, сбора метрик через `grpc_metrics.ClientStorage` и трейсинга
|
||||
|
||||
#### `RequestId() request.Middleware`
|
||||
|
||||
Middleware для автоматической генерации requestId для передачи в заголовках. Если в контексте будет указан requestId, то
|
||||
передаваться будет именно он.
|
||||
|
||||
#### `Log(logger log.Logger, logBody bool) request.Middleware`
|
||||
|
||||
Middleware для логирования запросов и ответов. Логирует тело запроса/ответа, если `logBody = true`.
|
||||
|
||||
#### `Metrics(storage MetricStorage) request.Middleware`
|
||||
|
||||
Middleware для сбора метрик длительности запросов.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type getUserRequest struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
cli, err := client.Default(client.Log(logger, true))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer cli.Close()
|
||||
|
||||
cli.Upgrade([]string{"host1:8080", "host2:9000"})
|
||||
|
||||
u := new(user)
|
||||
err = cli.Invoke("/get_user").
|
||||
ApplicationId(88).
|
||||
JsonRequestBody(getUserRequest{Id: "some-user-id"}).
|
||||
JsonResponseBody(u).
|
||||
Timeout(5 * time.Second).
|
||||
Do(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
log.Printf("username: %s\n", u.Name)
|
||||
}
|
||||
|
||||
```
|
||||
-159
@@ -1,159 +0,0 @@
|
||||
// Package request provides a fluent builder for constructing and executing gRPC requests.
|
||||
// It handles JSON marshaling/unmarshaling, metadata management, and timeout configuration.
|
||||
package request
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultTimeout is the default request timeout when none is specified.
|
||||
defaultTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
type EncodeSettings struct {
|
||||
EncodeRequest bool
|
||||
EncodeThreshold int
|
||||
AcceptEncodedResponse bool
|
||||
}
|
||||
|
||||
// Builder provides a fluent API for constructing and executing gRPC requests.
|
||||
// It handles JSON marshaling, metadata management, and timeout configuration.
|
||||
// Builder is not safe for concurrent use; create a new instance for each request.
|
||||
type Builder struct {
|
||||
Endpoint string
|
||||
MD metadata.MD
|
||||
EncodeSettings EncodeSettings
|
||||
|
||||
requestBody any
|
||||
responsePtr any
|
||||
applicationId int
|
||||
timeout time.Duration
|
||||
roundTripper RoundTripper
|
||||
}
|
||||
|
||||
// NewBuilder creates a new Builder for the specified endpoint.
|
||||
// Initializes with default timeout and empty metadata.
|
||||
func NewBuilder(
|
||||
roundTripper RoundTripper,
|
||||
endpoint string,
|
||||
encodeSettings EncodeSettings,
|
||||
) *Builder {
|
||||
return &Builder{
|
||||
Endpoint: endpoint,
|
||||
MD: metadata.New(make(map[string]string)),
|
||||
roundTripper: roundTripper,
|
||||
timeout: defaultTimeout,
|
||||
EncodeSettings: encodeSettings,
|
||||
}
|
||||
}
|
||||
|
||||
// ApplicationId sets the application identity header for the request.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) ApplicationId(appId int) *Builder {
|
||||
req.applicationId = appId
|
||||
return req
|
||||
}
|
||||
|
||||
// JsonRequestBody sets the request body as a JSON-encodable value.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) JsonRequestBody(reqBody any) *Builder {
|
||||
req.requestBody = reqBody
|
||||
return req
|
||||
}
|
||||
|
||||
// JsonResponseBody sets the pointer to unmarshal the JSON response into.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) JsonResponseBody(respPtr any) *Builder {
|
||||
req.responsePtr = respPtr
|
||||
return req
|
||||
}
|
||||
|
||||
// Timeout sets the request timeout duration.
|
||||
// A timeout of zero or negative disables the timeout.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) Timeout(timeout time.Duration) *Builder {
|
||||
req.timeout = timeout
|
||||
return req
|
||||
}
|
||||
|
||||
// AppendMetadata adds one or more values to the metadata key.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) AppendMetadata(k string, v ...string) *Builder {
|
||||
req.MD[k] = append(req.MD[k], v...)
|
||||
return req
|
||||
}
|
||||
|
||||
// EncodeRequest sets encoding for request body.
|
||||
// It affects content-encoding and request body serialization.
|
||||
func (b *Builder) EncodeRequest(encode bool) *Builder {
|
||||
b.EncodeSettings.EncodeRequest = encode
|
||||
return b
|
||||
}
|
||||
|
||||
// AcceptEncodedResponse enables transparent handling of encoded GRPC responses.
|
||||
//
|
||||
// When enabled, the client adds "accept-encoding" (e.g. zstd) to request headers,
|
||||
// allowing the server to return encoded payloads.
|
||||
func (b *Builder) AcceptEncodedResponse(accept bool) *Builder {
|
||||
b.EncodeSettings.AcceptEncodedResponse = accept
|
||||
return b
|
||||
}
|
||||
|
||||
// EncodeThreshold sets the request encoding threshold in bytes.
|
||||
func (b *Builder) EncodeThreshold(thresholdBytes int) *Builder {
|
||||
b.EncodeSettings.EncodeThreshold = thresholdBytes
|
||||
return b
|
||||
}
|
||||
|
||||
// Do executes the request and unmarshals the response if a response pointer was provided.
|
||||
// Returns an error if JSON marshaling, request execution, or response unmarshaling fails.
|
||||
// Automatically applies the configured timeout to the request context.
|
||||
func (req *Builder) Do(ctx context.Context) error {
|
||||
var (
|
||||
reqCtx = ctx
|
||||
cancel context.CancelFunc
|
||||
)
|
||||
if req.timeout > 0 {
|
||||
reqCtx, cancel = context.WithTimeout(ctx, req.timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
req.MD.Set(grpc.ProxyMethodNameHeader, req.Endpoint)
|
||||
if req.applicationId != 0 {
|
||||
req.MD.Set(grpc.ApplicationIdHeader, strconv.Itoa(req.applicationId))
|
||||
}
|
||||
ctx = metadata.NewOutgoingContext(reqCtx, req.MD)
|
||||
|
||||
var body []byte
|
||||
var err error
|
||||
if req.requestBody != nil {
|
||||
body, err = json.Marshal(req.requestBody)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal to json request body")
|
||||
}
|
||||
}
|
||||
message := &isp.Message{Body: &isp.Message_BytesBody{BytesBody: body}}
|
||||
|
||||
resp, err := req.roundTripper(ctx, req, message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if req.responsePtr != nil {
|
||||
err = json.Unmarshal(resp.GetBytesBody(), req.responsePtr)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "unmarshal response body")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// RoundTripper defines the interface for executing gRPC requests.
|
||||
// Receives a context, request builder, and message; returns a response message and optional error.
|
||||
// Used as the base for middleware chains.
|
||||
type RoundTripper func(ctx context.Context, builder *Builder, message *isp.Message) (*isp.Message, error)
|
||||
|
||||
// Middleware wraps a RoundTripper to add cross-cutting concerns like logging,
|
||||
// metrics, authentication, or error handling.
|
||||
// Middleware functions are typically chained in reverse order of execution.
|
||||
type Middleware func(next RoundTripper) RoundTripper
|
||||
-268
@@ -1,268 +0,0 @@
|
||||
# Package `endpoint`
|
||||
|
||||
Пакет `endpoint` предоставляет инструменты для создания gRPC-обработчиков с автоматической сериализацией JSON,
|
||||
валидацией запросов, middleware-цепочками и интеграцией метрик/логирования. Реализует паттерн "Endpoint" для изоляции
|
||||
бизнес-логики от транспортного слоя.
|
||||
|
||||
## Types
|
||||
|
||||
### Wrapper
|
||||
|
||||
Основная структура для создания цепочек обработки запросов. Объединяет:
|
||||
|
||||
- Маппинг параметров
|
||||
- Middleware (логирование, метрики, восстановление после паник)
|
||||
- Сериализацию/валидацию JSON
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewWrapper(paramMappers []ParamMapper, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper) Wrapper`
|
||||
|
||||
Создает конфигурацию для обработчиков.
|
||||
Параметры:
|
||||
|
||||
- `paramMappers` – правила извлечения параметров из контекста/метаданных
|
||||
- `bodyExtractor` – десериализация и валидация тела запроса
|
||||
- `bodyMapper` – сериализация ответа
|
||||
|
||||
#### `(m Wrapper) Endpoint(f any) grpc.HandlerFunc`
|
||||
|
||||
Преобразует пользовательскую функцию в gRPC-обработчик.
|
||||
Функция `f` может содержать параметры:
|
||||
|
||||
- `context.Context`
|
||||
- `grpc.AuthData` (метаданные аутентификации)
|
||||
- Пользовательский тип (десериализуется из JSON-тела)
|
||||
|
||||
#### `(m Wrapper) WithMiddlewares(middlewares ...grpc.Middleware) Wrapper`
|
||||
|
||||
Добавляет middleware в цепочку обработки.
|
||||
|
||||
### Caller
|
||||
|
||||
Внутренняя структура для вызова пользовательских обработчиков. Автоматически:
|
||||
|
||||
- Извлекает параметры
|
||||
- Вызывает middleware
|
||||
- Обрабатывает ошибки
|
||||
|
||||
**Methods:**
|
||||
|
||||
####
|
||||
|
||||
`NewCaller(f any,bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, paramMappers map[string]ParamMapper) (*Caller, error)`
|
||||
|
||||
Создает экземпляр `Caller` для функции-обработчика.
|
||||
|
||||
#### `(h *Caller) Handle(ctx context.Context, message *isp.Message) (*isp.Message, error)`
|
||||
|
||||
Вызывает функцию-обработчик, передавая ей аргументы, извлеченные из запроса.
|
||||
|
||||
### JsonRequestExtractor
|
||||
|
||||
Реализация интерфейса `RequestBodyExtractor` для работы с JSON. Валидирует данные с помощью объекта, реализующего
|
||||
интерфейс `Validator`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
####
|
||||
|
||||
`(j JsonRequestExtractor) Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error)`
|
||||
|
||||
Десериализует и валидирует JSON-тело запроса через `Validator`.
|
||||
|
||||
### JsonResponseMapper
|
||||
|
||||
Сериализует ответ обработчика в JSON-тело gRPC-сообщения.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(j JsonResponseMapper) Map(result any) (*isp.Message, error)`
|
||||
|
||||
Конвертирует результат обработчика в gRPC-сообщение в формате JSON.
|
||||
|
||||
## Middlewares
|
||||
|
||||
### `MaxRequestBodySize`
|
||||
|
||||
Ограничивает размер тела запроса (по умолчанию 64 МБ).
|
||||
|
||||
### `RequestId`
|
||||
|
||||
Добавляет в контекст requestId, который берет из заголовка x-request-id. Генерирует новый, если не находит.
|
||||
|
||||
### `DecodeRequest`
|
||||
Декодирует запрос при помощи переданного codec, если заголовок `x-content-encoding` совпадает с типом codec.
|
||||
|
||||
### `Metrics`
|
||||
|
||||
Собирает метрики: время выполнения, статусы, размеры тел.
|
||||
|
||||
### `Tracing`
|
||||
|
||||
Интеграция с трейсингом (OpenTelemetry).
|
||||
|
||||
### `EncodeResponse`
|
||||
|
||||
Кодирует ответ при помощи переданного codec, если заголовок `x-accept-encoding` содержит строку с типом codec (пример значения заголовка `"zstd, identity"`) и размер ответа больше переданного threshold'а, по умолчанию 128 КБ (параметр в байтах).
|
||||
|
||||
### `ErrorHandler`
|
||||
|
||||
Перехватывает и обрабатывает ошибки. Ошибки типа `GrpcError` возвращают структурированный ответ.
|
||||
Остальные ошибки логируются и возвращаются как Internal Server Error с gRPC-кодом 13.
|
||||
|
||||
### `Recovery`
|
||||
|
||||
Предотвращает падение сервера при панике в обработчике, преобразуя ее в ошибку.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `DefaultWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper`
|
||||
|
||||
Создает предварительно настроенную обертку (`Wrapper`) для gRPC-обработчиков с middleware и параметрами.
|
||||
Упрощает создание эндпоинтов, включая валидацию, метрики и обработку ошибок "из коробки".
|
||||
|
||||
Список Middleware:
|
||||
|
||||
- `RequestId`
|
||||
- `Metrics`
|
||||
- `Tracing`
|
||||
- `ErrorHandler`
|
||||
- `Recovery`
|
||||
|
||||
#### `DefaultCodecWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper`
|
||||
|
||||
Создает предварительно настроенную обертку (`Wrapper`) для gRPC-обработчиков с middleware и параметрами.
|
||||
Упрощает создание эндпоинтов, включая валидацию, декодирование запросов, кодировение ответов, метрики и обработку ошибок "из коробки".
|
||||
|
||||
Список Middleware:
|
||||
|
||||
- `RequestId`
|
||||
- `DecodeRequest`
|
||||
- `Metrics`
|
||||
- `Tracing`
|
||||
- `EncodeResponse`
|
||||
- `ErrorHandler`
|
||||
- `Recovery`
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type getUserRequest struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func getUser(ctx context.Context, authData grpc.AuthData, req getUserRequest) (*user, error) {
|
||||
appId, _ := authData.ApplicationId()
|
||||
log.Printf("Request from app with id %d", appId)
|
||||
|
||||
/* put here business logic */
|
||||
|
||||
return &user{Id: req.Id, Name: "Alice"}, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
mux := grpc.NewMux()
|
||||
wrapper := endpoint.DefaultWrapper(logger)
|
||||
mux.Handle("/get_user", wrapper.Endpoint(getUser))
|
||||
|
||||
srv := grpc.DefaultServer()
|
||||
srv.Upgrade(mux)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
srv.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err = srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Codec usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type getUserRequest struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func getUser(ctx context.Context, authData grpc.AuthData, req getUserRequest) (*user, error) {
|
||||
appId, _ := authData.ApplicationId()
|
||||
log.Printf("Request from app with id %d", appId)
|
||||
|
||||
/* put here business logic */
|
||||
|
||||
return &user{Id: req.Id, Name: "Alice"}, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
mux := grpc.NewMux()
|
||||
wrapper := endpoint.DefaultCodecWrapper(logger)
|
||||
mux.Handle("/get_user", wrapper.Endpoint(getUser))
|
||||
|
||||
srv := grpc.DefaultServer()
|
||||
srv.Upgrade(mux)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
srv.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err = srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
-124
@@ -1,124 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// param represents a single parameter to be injected into a wrapped function.
|
||||
type param struct {
|
||||
index int
|
||||
builder ParamBuilder
|
||||
}
|
||||
|
||||
// Caller wraps a function for gRPC invocation using reflection.
|
||||
// It analyzes the function signature, injects dependencies, and handles
|
||||
// request/response marshaling automatically.
|
||||
type Caller struct {
|
||||
bodyExtractor RequestBodyExtractor
|
||||
bodyMapper ResponseBodyMapper
|
||||
|
||||
handler reflect.Value
|
||||
paramsCount int
|
||||
params []param
|
||||
reqBodyIndex int
|
||||
reqBodyType reflect.Type
|
||||
|
||||
hasResult bool
|
||||
hasError bool
|
||||
errorIndex int
|
||||
}
|
||||
|
||||
// NewCaller creates a new Caller for the specified function.
|
||||
// Analyzes the function signature to determine parameter types and return values.
|
||||
// Returns an error if the input is not a function or if parameter types cannot be resolved.
|
||||
func NewCaller(
|
||||
f any,
|
||||
bodyExtractor RequestBodyExtractor,
|
||||
bodyMapper ResponseBodyMapper,
|
||||
paramMappers map[string]ParamMapper,
|
||||
) (*Caller, error) {
|
||||
rt := reflect.TypeOf(f)
|
||||
if rt.Kind() != reflect.Func {
|
||||
return nil, errors.New("function expected")
|
||||
}
|
||||
|
||||
paramsCount := rt.NumIn()
|
||||
reqBodyIndex := -1
|
||||
handler := reflect.ValueOf(f)
|
||||
var reqBodyType reflect.Type
|
||||
params := make([]param, 0, paramsCount)
|
||||
|
||||
for i := range paramsCount {
|
||||
p := rt.In(i)
|
||||
paramType := p.String()
|
||||
mapper, ok := paramMappers[paramType]
|
||||
|
||||
if !ok { // maybe it's a request body
|
||||
if reqBodyIndex != -1 {
|
||||
return nil, errors.Errorf("param mapper not found for type %s", paramType)
|
||||
}
|
||||
reqBodyIndex = i
|
||||
reqBodyType = p
|
||||
continue
|
||||
}
|
||||
|
||||
// it's a simple param
|
||||
params = append(params, param{index: i, builder: mapper.Builder})
|
||||
}
|
||||
|
||||
numOut := rt.NumOut()
|
||||
hasResult := numOut > 0 && rt.Out(0) != reflect.TypeFor[*error]().Elem()
|
||||
hasError := numOut > 0 && rt.Out(numOut-1) == reflect.TypeFor[*error]().Elem()
|
||||
|
||||
return &Caller{
|
||||
bodyExtractor: bodyExtractor,
|
||||
bodyMapper: bodyMapper,
|
||||
handler: handler,
|
||||
paramsCount: paramsCount,
|
||||
params: params,
|
||||
reqBodyIndex: reqBodyIndex,
|
||||
reqBodyType: reqBodyType,
|
||||
hasResult: hasResult,
|
||||
hasError: hasError,
|
||||
errorIndex: numOut - 1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Handle executes the wrapped function with the provided context and message.
|
||||
// Injects parameters, extracts request body, calls the function, and maps the result.
|
||||
// Returns the response message and any error from the function or parameter extraction.
|
||||
func (h *Caller) Handle(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
args := make([]reflect.Value, h.paramsCount)
|
||||
|
||||
if h.reqBodyIndex != -1 {
|
||||
value, err := h.bodyExtractor.Extract(ctx, message, h.reqBodyType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args[h.reqBodyIndex] = value
|
||||
}
|
||||
|
||||
for _, p := range h.params {
|
||||
value, err := p.builder(ctx, message)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args[p.index] = reflect.ValueOf(value)
|
||||
}
|
||||
|
||||
out := h.handler.Call(args)
|
||||
|
||||
if h.hasError && !out[h.errorIndex].IsNil() {
|
||||
return nil, out[h.errorIndex].Interface().(error) // nolint:forcetypeassert
|
||||
}
|
||||
|
||||
if h.hasResult {
|
||||
return h.bodyMapper.Map(out[0].Interface())
|
||||
}
|
||||
|
||||
return nil, nil // nolint:nilnil
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/grpc_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
)
|
||||
|
||||
// DefaultWrapper creates a Wrapper with pre-configured middleware for observability.
|
||||
// Includes request ID propagation, metrics collection, distributed tracing, error handling,
|
||||
// and panic recovery. Uses JSON for request extraction and response mapping.
|
||||
// Accepts additional middleware to be appended after the default ones.
|
||||
func DefaultWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper {
|
||||
paramMappers := []ParamMapper{
|
||||
ContextParam(),
|
||||
AuthDataParam(),
|
||||
}
|
||||
metricStorage := grpc_metrics.NewServerStorage(metrics.DefaultRegistry)
|
||||
middlewares := append(
|
||||
[]grpc.Middleware{
|
||||
RequestId(),
|
||||
Metrics(metricStorage),
|
||||
server_tracing.NewConfig().Middleware(),
|
||||
ErrorHandler(logger),
|
||||
Recovery(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
return NewWrapper(
|
||||
paramMappers,
|
||||
JsonRequestExtractor{Validator: validator.Default},
|
||||
JsonResponseMapper{},
|
||||
).WithMiddlewares(middlewares...)
|
||||
}
|
||||
|
||||
// DefaultCodecWrapper creates a Wrapper with pre-configured middleware for observability.
|
||||
// Includes request ID propagation, metrics collection, distributed tracing, error handling, encode response, decode request,
|
||||
// and panic recovery. Uses JSON for request extraction and response mapping.
|
||||
// Accepts additional middleware to be appended after the default ones.
|
||||
func DefaultCodecWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper {
|
||||
paramMappers := []ParamMapper{
|
||||
ContextParam(),
|
||||
AuthDataParam(),
|
||||
}
|
||||
metricStorage := grpc_metrics.NewServerStorage(metrics.DefaultRegistry)
|
||||
codec := codec.Default
|
||||
middlewares := append(
|
||||
[]grpc.Middleware{
|
||||
RequestId(),
|
||||
DecodeRequest(codec),
|
||||
Metrics(metricStorage),
|
||||
server_tracing.NewConfig().Middleware(),
|
||||
EncodeResponse(codec, defaultEncodeThreshold),
|
||||
ErrorHandler(logger),
|
||||
Recovery(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
return NewWrapper(
|
||||
paramMappers,
|
||||
JsonRequestExtractor{Validator: validator.Default},
|
||||
JsonResponseMapper{},
|
||||
).WithMiddlewares(middlewares...)
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"unicode"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
const (
|
||||
// errCodeBadRequest is the error code for invalid request body errors.
|
||||
errCodeBadRequest = 400
|
||||
)
|
||||
|
||||
// Validator defines the interface for request validation.
|
||||
// Implementations should validate a value and return whether it's valid
|
||||
// along with field-specific error details.
|
||||
type Validator interface {
|
||||
// Validate checks if the value is valid.
|
||||
// Returns true if valid, false otherwise, along with a map of field names to error messages.
|
||||
Validate(value any) (bool, map[string]string)
|
||||
}
|
||||
|
||||
// JsonRequestExtractor extracts and validates JSON request bodies from gRPC messages.
|
||||
// Unmarshals the message body into the target type and validates it using the configured validator.
|
||||
type JsonRequestExtractor struct {
|
||||
Validator Validator
|
||||
}
|
||||
|
||||
// Extract unmarshals the message body as JSON and validates it.
|
||||
// Returns a reflect.Value of the created instance or an error if unmarshaling or validation fails.
|
||||
// Business validation errors are returned as apierrors.BusinessError with code 400.
|
||||
func (j JsonRequestExtractor) Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error) {
|
||||
instance := reflect.New(reqBodyType)
|
||||
err := json.Unmarshal(message.GetBytesBody(), instance.Interface())
|
||||
if err != nil {
|
||||
err = errors.WithMessage(err, "unmarshal json request body")
|
||||
return reflect.Value{}, apierrors.NewBusinessError(errCodeBadRequest, err.Error(), err)
|
||||
}
|
||||
|
||||
elem := instance.Elem()
|
||||
|
||||
ok, details := j.Validator.Validate(elem.Interface())
|
||||
if ok {
|
||||
return elem, nil
|
||||
}
|
||||
formattedDetails := formatDetails(details)
|
||||
return reflect.Value{}, apierrors.NewBusinessError(
|
||||
errCodeBadRequest,
|
||||
"invalid request body",
|
||||
errors.Errorf("validation errors: %v", formattedDetails),
|
||||
).WithDetails(formattedDetails)
|
||||
}
|
||||
|
||||
// formatDetails converts a map of field error messages to a format suitable for API responses.
|
||||
// Converts field names to lowercase (first character) for consistency.
|
||||
func formatDetails(details map[string]string) map[string]any {
|
||||
result := make(map[string]any, len(details))
|
||||
for k, v := range details {
|
||||
arr := []rune(k)
|
||||
arr[0] = unicode.ToLower(arr[0])
|
||||
result[string(arr)] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
// JsonResponseMapper maps handler results to gRPC messages with JSON-encoded bodies.
|
||||
// Implements the ResponseBodyMapper interface.
|
||||
type JsonResponseMapper struct{}
|
||||
|
||||
// Map marshals the result to JSON and creates a gRPC message.
|
||||
// Returns an empty message body if result is nil.
|
||||
// Returns an error if JSON marshaling fails.
|
||||
func (j JsonResponseMapper) Map(result any) (*isp.Message, error) {
|
||||
if result == nil {
|
||||
return &isp.Message{Body: &isp.Message_BytesBody{}}, nil
|
||||
}
|
||||
data, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "marshal json")
|
||||
}
|
||||
return &isp.Message{
|
||||
Body: &isp.Message_BytesBody{
|
||||
BytesBody: data,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// MetricStorage defines the interface for collecting gRPC server metrics.
|
||||
// Implementations should record request durations, payload sizes, and response codes.
|
||||
type MetricStorage interface {
|
||||
// ObserveDuration records the duration of a request for the given method.
|
||||
ObserveDuration(method string, duration time.Duration)
|
||||
// ObserveRequestBodySize records the size of the request body.
|
||||
ObserveRequestBodySize(method string, size int)
|
||||
// ObserveResponseBodySize records the size of the response body.
|
||||
ObserveResponseBodySize(method string, size int)
|
||||
// CountStatusCode increments the counter for the given endpoint and status code.
|
||||
CountStatusCode(endpoint string, code codes.Code)
|
||||
}
|
||||
|
||||
// Metrics creates a middleware that collects metrics for gRPC server requests.
|
||||
// Records request duration, request/response body sizes, and response status codes.
|
||||
// The endpoint name is extracted from the ProxyMethodNameHeader in request metadata.
|
||||
func Metrics(storage MetricStorage) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
endpoint, err := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
storage.ObserveRequestBodySize(endpoint, len(message.GetBytesBody()))
|
||||
start := time.Now()
|
||||
response, err := next(ctx, message)
|
||||
storage.ObserveDuration(endpoint, time.Since(start))
|
||||
storage.CountStatusCode(endpoint, status.Code(err))
|
||||
if response != nil {
|
||||
storage.ObserveResponseBodySize(endpoint, len(response.GetBytesBody()))
|
||||
}
|
||||
|
||||
return response, err
|
||||
}
|
||||
}
|
||||
}
|
||||
-221
@@ -1,221 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/log/logutil"
|
||||
sentry2 "github.com/txix-open/isp-kit/observability/sentry"
|
||||
"github.com/txix-open/isp-kit/panic_recovery"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
grpc2 "google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEncodeThreshold = codec.DefaultEncodeThreshold
|
||||
)
|
||||
|
||||
// Recovery creates a middleware that catches panics and converts them to errors.
|
||||
// Prevents gRPC server crashes from handler panics by recovering and returning the error.
|
||||
func Recovery() grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (msg *isp.Message, err error) {
|
||||
defer panic_recovery.Recover(func(panicErr error) {
|
||||
err = panicErr
|
||||
})
|
||||
return next(ctx, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ErrorHandler creates a middleware that handles errors from downstream handlers.
|
||||
// Logs errors at appropriate levels, enriches them with Sentry context, and
|
||||
// converts custom GrpcError types to gRPC status errors.
|
||||
// Returns a generic "internal service error" for unknown error types to prevent
|
||||
// information leakage.
|
||||
func ErrorHandler(logger log.Logger) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
result, err := next(ctx, message)
|
||||
if err == nil {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
logFunc := logutil.LogLevelFuncForError(err, logger)
|
||||
logContext := sentry2.EnrichEvent(ctx, func(event *sentry.Event) {
|
||||
event.Request = sentryRequest(ctx)
|
||||
})
|
||||
logFunc(logContext, err)
|
||||
|
||||
var grpcErr GrpcError
|
||||
if errors.As(err, &grpcErr) {
|
||||
return result, grpcErr.GrpcStatusError()
|
||||
}
|
||||
|
||||
// deprecated approach
|
||||
_, ok := status.FromError(err)
|
||||
if ok {
|
||||
return result, err
|
||||
}
|
||||
|
||||
// hide error details to prevent potential security leaks
|
||||
return result, status.Error(codes.Internal, "internal service error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RequestId creates a middleware that manages request IDs for tracing.
|
||||
// Extracts the request ID from incoming metadata, generates a new one if absent,
|
||||
// and injects it into the context for downstream use.
|
||||
func RequestId() grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
values := md.Get(requestid.Header)
|
||||
requestId := ""
|
||||
if len(values) > 0 {
|
||||
requestId = values[0]
|
||||
}
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
}
|
||||
ctx = requestid.ToContext(ctx, requestId)
|
||||
ctx = log.ToContext(ctx, log.String(requestid.LogKey, requestId))
|
||||
|
||||
return next(ctx, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type DecodeCodec interface {
|
||||
Type() string
|
||||
DecodeBytes(b []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// DecodeRequest returns middleware that transparently handles decoded requests.
|
||||
//
|
||||
// If x-content-encoding matches codec, request body is decoded.
|
||||
//
|
||||
// Important:
|
||||
// - Should be placed before logging middleware if logs must see decoded data.
|
||||
func DecodeRequest(codec DecodeCodec) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, msg *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
|
||||
contentEncoding, _ := grpc.StringFromMd(grpc.ContentEncodingHeader, md)
|
||||
reqBody := msg.GetBytesBody()
|
||||
if contentEncoding == codec.Type() {
|
||||
decoded, err := codec.DecodeBytes(reqBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg.Body = &isp.Message_BytesBody{
|
||||
BytesBody: decoded,
|
||||
}
|
||||
md.Delete(grpc.ContentEncodingHeader)
|
||||
ctx = metadata.NewIncomingContext(ctx, md)
|
||||
}
|
||||
|
||||
return next(ctx, msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type EncodeCodec interface {
|
||||
Type() string
|
||||
EncodeBytes(b []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// EncodeResponse returns middleware that transparently handles response encoding.
|
||||
//
|
||||
// If client supports x-accept-encoding and response body size > encodeThresholdBytes,
|
||||
// the response is encoded using codec.
|
||||
//
|
||||
// Important:
|
||||
// - Should be placed before logging middleware if logs must see plain data.
|
||||
func EncodeResponse(codec EncodeCodec, encodeThresholdBytes int) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, msg *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
|
||||
resp, err := next(ctx, msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check accept
|
||||
acceptEncoding, _ := grpc.StringFromMd(grpc.AcceptEncodingHeader, md)
|
||||
if !acceptsEncoding(acceptEncoding, codec.Type()) {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
responseBody := resp.GetBytesBody()
|
||||
if len(responseBody) <= encodeThresholdBytes {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
err = grpc2.SetHeader(ctx, metadata.Pairs(
|
||||
grpc.ContentEncodingHeader, codec.Type(),
|
||||
))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
encoded, err := codec.EncodeBytes(responseBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &isp.Message_BytesBody{
|
||||
BytesBody: encoded,
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// acceptsEncoding split header and check contains encoding in it.
|
||||
func acceptsEncoding(header, encoding string) bool {
|
||||
for part := range strings.SplitSeq(header, ",") {
|
||||
if strings.TrimSpace(part) == encoding {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// sentryRequest creates a Sentry request object from the gRPC context.
|
||||
// Extracts endpoint and application ID from metadata for error tracking.
|
||||
func sentryRequest(ctx context.Context) *sentry.Request {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
endpoint, _ := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md)
|
||||
applicationId, _ := grpc.StringFromMd(grpc.ApplicationIdHeader, md)
|
||||
return &sentry.Request{
|
||||
URL: endpoint,
|
||||
Method: "POST",
|
||||
Headers: map[string]string{
|
||||
grpc.ApplicationIdHeader: applicationId,
|
||||
},
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// ContextParam creates a ParamMapper for injecting context.Context into handlers.
|
||||
// The context is passed through from the incoming gRPC request context.
|
||||
func ContextParam() ParamMapper {
|
||||
return ParamMapper{
|
||||
Type: "context.Context",
|
||||
Builder: func(ctx context.Context, message *isp.Message) (any, error) {
|
||||
return ctx, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// AuthDataParam creates a ParamMapper for injecting grpc.AuthData into handlers.
|
||||
// Extracts authentication and authorization information from the incoming request metadata.
|
||||
// Returns an error if metadata is not present in the context.
|
||||
func AuthDataParam() ParamMapper {
|
||||
return ParamMapper{
|
||||
Type: "grpc.AuthData",
|
||||
Builder: func(ctx context.Context, message *isp.Message) (any, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context") // nolint:err113
|
||||
}
|
||||
return grpc.AuthData(md), nil
|
||||
},
|
||||
}
|
||||
}
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
// Package endpoint provides a higher-level abstraction for building gRPC handlers.
|
||||
// It enables reflection-based function wrapping with automatic request/response
|
||||
// marshaling, parameter injection, and middleware support.
|
||||
//
|
||||
// The package integrates with the ISP kit framework's logging, metrics, and
|
||||
// validation systems for comprehensive observability and error handling.
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"slices"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// GrpcError is an interface for errors that can be converted to gRPC status errors.
|
||||
// Implementations should return a gRPC status error with appropriate details.
|
||||
type GrpcError interface {
|
||||
GrpcStatusError() error
|
||||
}
|
||||
|
||||
// RequestBodyExtractor defines the interface for extracting request bodies from gRPC messages.
|
||||
// Implementations should unmarshal the message body into the target type and return a reflect.Value.
|
||||
type RequestBodyExtractor interface {
|
||||
// Extract unmarshals the message body into an instance of reqBodyType.
|
||||
// Returns the reflect.Value of the created instance and any unmarshaling or validation errors.
|
||||
Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error)
|
||||
}
|
||||
|
||||
// ResponseBodyMapper defines the interface for mapping handler results to gRPC messages.
|
||||
// Implementations should marshal the result into a gRPC message body.
|
||||
type ResponseBodyMapper interface {
|
||||
// Map converts a handler result into a gRPC message.
|
||||
// Returns the message and any marshaling errors.
|
||||
Map(result any) (*isp.Message, error)
|
||||
}
|
||||
|
||||
// ParamBuilder defines a function that builds a parameter value from context and message.
|
||||
// Used by ParamMapper to inject dependencies like context, auth data, etc.
|
||||
type ParamBuilder func(ctx context.Context, message *isp.Message) (any, error)
|
||||
|
||||
// ParamMapper maps a parameter type string to a builder function.
|
||||
// Used to inject dependencies into handler functions automatically.
|
||||
type ParamMapper struct {
|
||||
// Type is the string representation of the parameter type.
|
||||
Type string
|
||||
// Builder is the function that creates the parameter value.
|
||||
Builder ParamBuilder
|
||||
}
|
||||
|
||||
// Wrapper is a high-level handler factory that wraps functions with middleware and
|
||||
// automatic request/response handling. It uses reflection to analyze function signatures
|
||||
// and inject dependencies like context and auth data.
|
||||
type Wrapper struct {
|
||||
ParamMappers map[string]ParamMapper
|
||||
BodyExtractor RequestBodyExtractor
|
||||
BodyMapper ResponseBodyMapper
|
||||
Middlewares []grpc.Middleware
|
||||
}
|
||||
|
||||
// NewWrapper creates a new Wrapper with the specified configuration.
|
||||
// Accepts variadic paramMappers, a body extractor, and a body mapper.
|
||||
func NewWrapper(
|
||||
paramMappers []ParamMapper,
|
||||
bodyExtractor RequestBodyExtractor,
|
||||
bodyMapper ResponseBodyMapper,
|
||||
) Wrapper {
|
||||
mappers := make(map[string]ParamMapper)
|
||||
for _, mapper := range paramMappers {
|
||||
mappers[mapper.Type] = mapper
|
||||
}
|
||||
return Wrapper{
|
||||
ParamMappers: mappers,
|
||||
BodyExtractor: bodyExtractor,
|
||||
BodyMapper: bodyMapper,
|
||||
}
|
||||
}
|
||||
|
||||
// Endpoint wraps a function to create a gRPC HandlerFunc.
|
||||
// The function is analyzed via reflection to determine parameter types and return values.
|
||||
// Middleware is applied in reverse order (last added, first executed).
|
||||
// Panics if the function signature is invalid or cannot be wrapped.
|
||||
func (m Wrapper) Endpoint(f any) grpc.HandlerFunc {
|
||||
caller, err := NewCaller(f, m.BodyExtractor, m.BodyMapper, m.ParamMappers)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
handler := caller.Handle
|
||||
for i := range slices.Backward(m.Middlewares) {
|
||||
handler = m.Middlewares[i](handler)
|
||||
}
|
||||
return handler
|
||||
}
|
||||
|
||||
// WithMiddlewares returns a new Wrapper with additional middleware appended.
|
||||
// The original Wrapper is not modified.
|
||||
func (m Wrapper) WithMiddlewares(middlewares ...grpc.Middleware) Wrapper {
|
||||
return Wrapper{
|
||||
ParamMappers: m.ParamMappers,
|
||||
BodyExtractor: m.BodyExtractor,
|
||||
BodyMapper: m.BodyMapper,
|
||||
Middlewares: append(m.Middlewares, middlewares...),
|
||||
}
|
||||
}
|
||||
-112
@@ -1,112 +0,0 @@
|
||||
# Package `grpc_metrics`
|
||||
|
||||
Пакет `grpc_metrics` предоставляет средства для мониторинга метрик GRPC-клиентов и серверов.
|
||||
|
||||
## Types
|
||||
|
||||
### ClientStorage
|
||||
|
||||
Хранилище метрик GRPC-клиента.
|
||||
|
||||
**Metrics:**
|
||||
|
||||
#### `grpc_client_request_duration_ms{endpoint="..."}`
|
||||
|
||||
Продолжительность вызова внешнего GRPC-сервиса.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `func NewClientStorage(reg *metrics.Registry) *ClientStorage`
|
||||
|
||||
Создаёт и регистрирует метрику `client_request_duration_ms` с лейблом `endpoint` в переданном реестре.
|
||||
|
||||
#### `func (s *ClientStorage) ObserveDuration(endpoint string, duration time.Duration)`
|
||||
|
||||
Регистрирует длительность GRPC-вызова для заданного `endpoint`.
|
||||
|
||||
### ServerStorage
|
||||
|
||||
Хранилище метрик GRPC-сервера.
|
||||
|
||||
**Metrics:**
|
||||
|
||||
#### `grpc_request_duration_ms{endpoint="..."}`
|
||||
|
||||
Продолжительность обработки входящего GRPC-запроса.
|
||||
|
||||
#### `grpc_request_body_size{endpoint="..."}`
|
||||
|
||||
Размер тела входящего запроса.
|
||||
|
||||
#### `grpc_response_body_size{endpoint="..."}`
|
||||
|
||||
Размер тела ответа.
|
||||
|
||||
#### `grpc_status_code_count{endpoint="...",code="..."}`
|
||||
|
||||
Количество ответов по статус-кодам (`OK`, `InvalidArgument`, и т.д.).
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `func NewServerStorage(reg *metrics.Registry) *ServerStorage`
|
||||
|
||||
Создаёт и регистрирует все метрики сервера с нужными лейблами в переданном реестре.
|
||||
|
||||
#### `func (s *ServerStorage) ObserveDuration(endpoint string, duration time.Duration)`
|
||||
|
||||
Регистрирует длительность обработки GRPC-запроса для `endpoint`.
|
||||
|
||||
#### `func (s *ServerStorage) ObserveRequestBodySize(endpoint string, size int)`
|
||||
|
||||
Регистрирует размер тела запроса в байтах.
|
||||
|
||||
#### `func (s *ServerStorage) ObserveResponseBodySize(endpoint string, size int)`
|
||||
|
||||
Регистрирует размер тела ответа в байтах.
|
||||
|
||||
#### `func (s *ServerStorage) CountStatusCode(endpoint string, code codes.Code)`
|
||||
|
||||
Увеличивает счётчик ответов с соответствующим GRPC-кодом.
|
||||
|
||||
## Prometheus metrics example
|
||||
|
||||
```
|
||||
# HELP grpc_client_request_duration_ms The latencies of calling external services via GRPC
|
||||
# TYPE grpc_client_request_duration_ms summary
|
||||
grpc_client_request_duration_ms{endpoint="UserService.GetUser"} 12.3
|
||||
|
||||
# HELP grpc_request_duration_ms The latency of the GRPC requests
|
||||
# TYPE grpc_request_duration_ms summary
|
||||
grpc_request_duration_ms{endpoint="UserService.GetUser"} 10.5
|
||||
|
||||
# HELP grpc_request_body_size The size of request body
|
||||
# TYPE grpc_request_body_size summary
|
||||
grpc_request_body_size{endpoint="UserService.GetUser"} 512
|
||||
|
||||
# HELP grpc_response_body_size The size of response body
|
||||
# TYPE grpc_response_body_size summary
|
||||
grpc_response_body_size{endpoint="UserService.GetUser"} 1024
|
||||
|
||||
# HELP grpc_status_code_count Counter of statuses codes
|
||||
# TYPE grpc_status_code_count counter
|
||||
grpc_status_code_count{endpoint="UserService.GetUser",code="OK"} 32
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
clientMetrics := grpc_metrics.NewClientStorage(metrics.DefaultRegistry)
|
||||
defer func(start time.Time) {
|
||||
clientMetrics.ObserveDuration("UserService.GetUser", time.Since(start))
|
||||
}(time.Now())
|
||||
|
||||
// ... GRPC call
|
||||
|
||||
serverMetrics := grpc_metrics.NewServerStorage(metrics.DefaultRegistry)
|
||||
serverMetrics.ObserveDuration("UserService.GetUser", 12*time.Millisecond)
|
||||
serverMetrics.ObserveRequestBodySize("UserService.GetUser", 512)
|
||||
serverMetrics.ObserveResponseBodySize("UserService.GetUser", 1024)
|
||||
serverMetrics.CountStatusCode("UserService.GetUser", codes.OK)
|
||||
```
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package grpc_metrics
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
)
|
||||
|
||||
// ClientStorage collects metrics for gRPC client operations, primarily focusing
|
||||
// on request latency when calling external gRPC services.
|
||||
type ClientStorage struct {
|
||||
duration *prometheus.SummaryVec
|
||||
}
|
||||
|
||||
// NewClientStorage creates a new ClientStorage instance and registers its metrics
|
||||
// with the provided registry. Metrics are labeled by the gRPC endpoint.
|
||||
func NewClientStorage(reg *metrics.Registry) *ClientStorage {
|
||||
s := &ClientStorage{
|
||||
duration: metrics.GetOrRegister(reg, prometheus.NewSummaryVec(prometheus.SummaryOpts{
|
||||
Subsystem: "grpc",
|
||||
Name: "client_request_duration_ms",
|
||||
Help: "The latencies of calling external services via GRPC",
|
||||
Objectives: metrics.DefaultObjectives,
|
||||
}, []string{"endpoint"})),
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ObserveDuration records the latency of a gRPC client request, labeled by endpoint.
|
||||
func (s *ClientStorage) ObserveDuration(endpoint string, duration time.Duration) {
|
||||
s.duration.WithLabelValues(endpoint).Observe(metrics.Milliseconds(duration))
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
// Package grpc_metrics provides Prometheus metric collectors for gRPC server and client operations.
|
||||
// It tracks request latencies, body sizes, and status code counts for both incoming gRPC requests
|
||||
// and outgoing gRPC client calls.
|
||||
//
|
||||
// Example usage for gRPC server:
|
||||
//
|
||||
// serverStorage := grpc_metrics.NewServerStorage(reg)
|
||||
// serverStorage.ObserveDuration(endpoint, duration)
|
||||
// serverStorage.CountStatusCode(endpoint, code)
|
||||
//
|
||||
// Example usage for gRPC client:
|
||||
//
|
||||
// clientStorage := grpc_metrics.NewClientStorage(reg)
|
||||
// clientStorage.ObserveDuration(endpoint, duration)
|
||||
package grpc_metrics
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
package grpc_metrics
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
// ServerStorage collects metrics for gRPC server operations, including request
|
||||
// latency, request/response body sizes, and gRPC status code counts.
|
||||
type ServerStorage struct {
|
||||
duration *prometheus.SummaryVec
|
||||
requestBodySize *prometheus.SummaryVec
|
||||
responseBodySize *prometheus.SummaryVec
|
||||
statusCounter *prometheus.CounterVec
|
||||
}
|
||||
|
||||
// NewServerStorage creates a new ServerStorage instance and registers its metrics
|
||||
// with the provided registry. Metrics are labeled by gRPC endpoint.
|
||||
func NewServerStorage(reg *metrics.Registry) *ServerStorage {
|
||||
s := &ServerStorage{
|
||||
duration: metrics.GetOrRegister(reg, prometheus.NewSummaryVec(prometheus.SummaryOpts{
|
||||
Subsystem: "grpc",
|
||||
Name: "request_duration_ms",
|
||||
Help: "The latency of the GRPC requests",
|
||||
Objectives: metrics.DefaultObjectives,
|
||||
}, []string{"endpoint"})),
|
||||
requestBodySize: metrics.GetOrRegister(reg, prometheus.NewSummaryVec(prometheus.SummaryOpts{
|
||||
Subsystem: "grpc",
|
||||
Name: "request_body_size",
|
||||
Help: "The size of request body",
|
||||
Objectives: metrics.DefaultObjectives,
|
||||
}, []string{"endpoint"})),
|
||||
responseBodySize: metrics.GetOrRegister(reg, prometheus.NewSummaryVec(prometheus.SummaryOpts{
|
||||
Subsystem: "grpc",
|
||||
Name: "response_body_size",
|
||||
Help: "The size of response body",
|
||||
Objectives: metrics.DefaultObjectives,
|
||||
}, []string{"endpoint"})),
|
||||
statusCounter: metrics.GetOrRegister(reg, prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Subsystem: "grpc",
|
||||
Name: "status_code_count",
|
||||
Help: "Counter of statuses codes",
|
||||
}, []string{"endpoint", "code"})),
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// ObserveDuration records the latency of a gRPC request, labeled by endpoint.
|
||||
func (s *ServerStorage) ObserveDuration(endpoint string, duration time.Duration) {
|
||||
s.duration.WithLabelValues(endpoint).Observe(metrics.Milliseconds(duration))
|
||||
}
|
||||
|
||||
// ObserveRequestBodySize records the size of a gRPC request payload in bytes.
|
||||
func (s *ServerStorage) ObserveRequestBodySize(endpoint string, size int) {
|
||||
s.requestBodySize.WithLabelValues(endpoint).Observe(float64(size))
|
||||
}
|
||||
|
||||
// ObserveResponseBodySize records the size of a gRPC response payload in bytes.
|
||||
func (s *ServerStorage) ObserveResponseBodySize(endpoint string, size int) {
|
||||
s.responseBodySize.WithLabelValues(endpoint).Observe(float64(size))
|
||||
}
|
||||
|
||||
// CountStatusCode increments the counter for a specific gRPC status code,
|
||||
// labeled by endpoint and status code.
|
||||
func (s *ServerStorage) CountStatusCode(endpoint string, code codes.Code) {
|
||||
s.statusCounter.WithLabelValues(endpoint, code.String()).Inc()
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
// Package grpc provides utilities for gRPC tracing integration.
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// MetadataCarrier implements the TextMapCarrier interface for gRPC metadata.
|
||||
type MetadataCarrier metadata.MD
|
||||
|
||||
// Get returns the first value associated with the given key.
|
||||
func (m MetadataCarrier) Get(key string) string {
|
||||
value := metadata.MD(m).Get(key)
|
||||
if len(value) == 0 {
|
||||
return ""
|
||||
}
|
||||
return value[0]
|
||||
}
|
||||
|
||||
// Set associates a key-value pair in the metadata.
|
||||
func (m MetadataCarrier) Set(key string, value string) {
|
||||
metadata.MD(m).Set(key, value)
|
||||
}
|
||||
|
||||
// Keys returns all keys in the metadata.
|
||||
func (m MetadataCarrier) Keys() []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for key := range m {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
Generated
Vendored
-62
@@ -1,62 +0,0 @@
|
||||
# Package `client_tracing`
|
||||
|
||||
Пакет `client_tracing` предназначен для добавления middleware к gRPC-клиенту с поддержкой распределённой трассировки через OpenTelemetry. Позволяет автоматически создавать и передавать span-контекст при выполнении gRPC-запросов, а также записывать статусы и ошибки вызовов в трассировку.
|
||||
|
||||
## Types
|
||||
|
||||
### Config
|
||||
|
||||
Структура `Config` представляет конфигурацию трассировки для gRPC-клиента.
|
||||
|
||||
**Fields:**
|
||||
|
||||
#### `Provider`
|
||||
|
||||
Реализация интерфейса `tracing.TracerProvider`, используемая для создания спанов.
|
||||
|
||||
#### `Propagator`
|
||||
|
||||
Реализация интерфейса `tracing.Propagator`, используемая для инъекции и извлечения контекста трассировки.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `func NewConfig() Config`
|
||||
|
||||
Создаёт конфигурацию трассировки с `provider` и `propagator` по умолчанию.
|
||||
|
||||
#### `func (c Config) Middleware() request.Middleware`
|
||||
|
||||
Возвращает middleware для клиента gRPC, реализующего трассировку запроса. Если трассировка отключена (noop-провайдер), возвращается middleware-заглушка.
|
||||
|
||||
Middleware:
|
||||
|
||||
- Создаёт новый спан для каждого gRPC-вызова с именем `GRPC call <endpoint>`.
|
||||
- Устанавливает `span kind` в значение `Client`.
|
||||
- Добавляет `request_id` в атрибуты спана.
|
||||
- Инъецирует контекст в metadata запроса.
|
||||
- В случае ошибки записывает её в спан и устанавливает статус `Error`.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing"
|
||||
)
|
||||
func main() {
|
||||
...
|
||||
cfg := client_tracing.NewConfig()
|
||||
client := client.New(
|
||||
client.WithMiddleware(
|
||||
cfg.Middleware(),
|
||||
),
|
||||
)
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Для корректной работы необходимо, чтобы в контексте присутствовал `request_id`, а также был корректно настроен глобальный TracerProvider и Propagator OpenTelemetry.
|
||||
Generated
Vendored
-77
@@ -1,77 +0,0 @@
|
||||
// Package client_tracing provides gRPC client middleware for distributed tracing.
|
||||
package client_tracing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/observability/tracing"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// tracerName identifies the tracer for gRPC client tracing.
|
||||
const tracerName = "isp-kit/observability/tracing/grpc"
|
||||
|
||||
// Config holds the configuration for the gRPC client tracing middleware.
|
||||
type Config struct {
|
||||
// Provider is the tracer provider used to create tracers.
|
||||
Provider tracing.TracerProvider
|
||||
// Propagator is the text map propagator for context propagation.
|
||||
Propagator tracing.Propagator
|
||||
}
|
||||
|
||||
// NewConfig creates a new Config with default values.
|
||||
func NewConfig() Config {
|
||||
return Config{
|
||||
Provider: tracing.DefaultProvider,
|
||||
Propagator: tracing.DefaultPropagator,
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware returns a gRPC client middleware that creates spans for outgoing RPC calls.
|
||||
// It injects trace context into the request metadata, creates a client span, and records
|
||||
// errors. If the provider is a no-op, it returns a pass-through middleware.
|
||||
func (c Config) Middleware() request.Middleware {
|
||||
if tracing.IsNoop(c.Provider) {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
return next(ctx, builder, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracer := c.Provider.Tracer(tracerName)
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
attributes := []attribute.KeyValue{
|
||||
tracing.RequestId.String(requestid.FromContext(ctx)),
|
||||
}
|
||||
opts := []trace.SpanStartOption{
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attributes...),
|
||||
}
|
||||
|
||||
clientEndpoint := builder.Endpoint
|
||||
spanName := fmt.Sprintf("GRPC call %s", clientEndpoint)
|
||||
|
||||
ctx, span := tracer.Start(ctx, spanName, opts...)
|
||||
defer span.End()
|
||||
|
||||
c.Propagator.Inject(ctx, grpc.MetadataCarrier(builder.MD))
|
||||
|
||||
resp, err := next(ctx, builder, message)
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
}
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
Vendored
-95
@@ -1,95 +0,0 @@
|
||||
# Package `server_tracing`
|
||||
|
||||
Пакет `server_tracing` предоставляет middleware для серверов gRPC, реализующих трассировку входящих запросов с использованием OpenTelemetry.
|
||||
|
||||
## Types
|
||||
|
||||
### Config
|
||||
|
||||
Структура `Config` предназначена для конфигурации middleware трассировки gRPC-сервера. Она содержит провайдер трассировки и пропагатор контекста.
|
||||
|
||||
**Fields:**
|
||||
|
||||
#### `Provider tracing.TracerProvider`
|
||||
|
||||
Реализация интерфейса `tracing.TracerProvider`, используемая для создания спанов.
|
||||
|
||||
#### `Propagator tracing.Propagator`
|
||||
|
||||
Реализация интерфейса `tracing.Propagator`, используемая для инъекции и извлечения контекста трассировки.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `func NewConfig() Config`
|
||||
|
||||
Создаёт конфигурацию трассировки с `provider` и `propagator` по умолчанию.
|
||||
|
||||
#### `func (c Config) Middleware() grpc.Middleware`
|
||||
|
||||
Создаёт middleware для трассировки gRPC-запросов. Возвращаемый middleware:
|
||||
|
||||
- Извлекает контекст трассировки из входящих метаданных;
|
||||
- Инициирует span с именем, основанным на методе gRPC-запроса (если доступно);
|
||||
- Добавляет атрибут `request.id`;
|
||||
- Фиксирует ошибку в span, если она произошла;
|
||||
- Завершает span после выполнения запроса.
|
||||
|
||||
Если трассировка отключена (noop-провайдер), возвращается no-op middleware.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing"
|
||||
)
|
||||
|
||||
func main(){
|
||||
...
|
||||
|
||||
tracingCfg := server_tracing.NewConfig()
|
||||
server := grpc.DefaultServer()
|
||||
|
||||
logger, _ := log.New()
|
||||
paramMappers := []endpoint.ParamMapper{
|
||||
ContextParam(),
|
||||
AuthDataParam(),
|
||||
}
|
||||
middlewares := append(
|
||||
[]grpc.Middleware{
|
||||
RequestId(),
|
||||
server_tracing.NewConfig().Middleware(),
|
||||
ErrorHandler(logger),
|
||||
Recovery(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
wrapper := NewWrapper(
|
||||
paramMappers,
|
||||
JsonRequestExtractor{Validator: validator.Default},
|
||||
JsonResponseMapper{},
|
||||
).WithMiddlewares(middlewares...)
|
||||
|
||||
mux := grpc.NewMux()
|
||||
mux.Handle("some_endpoint", wrapper.Endpoint(func(ctx context.Context) error {
|
||||
// реализация
|
||||
return nil
|
||||
}))
|
||||
|
||||
server.Upgrade(mux)
|
||||
|
||||
server.ListenAndServe(":8080")
|
||||
}
|
||||
```
|
||||
Generated
Vendored
-87
@@ -1,87 +0,0 @@
|
||||
// Package server_tracing provides gRPC server middleware for distributed tracing.
|
||||
package server_tracing
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/log/logutil"
|
||||
"github.com/txix-open/isp-kit/observability/tracing"
|
||||
grpc2 "github.com/txix-open/isp-kit/observability/tracing/grpc"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// tracerName identifies the tracer for gRPC server tracing.
|
||||
const tracerName = "isp-kit/observability/tracing/grpc"
|
||||
|
||||
// Config holds the configuration for the gRPC server tracing middleware.
|
||||
type Config struct {
|
||||
// Provider is the tracer provider used to create tracers.
|
||||
Provider tracing.TracerProvider
|
||||
// Propagator is the text map propagator for context propagation.
|
||||
Propagator tracing.Propagator
|
||||
}
|
||||
|
||||
// NewConfig creates a new Config with default values.
|
||||
func NewConfig() Config {
|
||||
return Config{
|
||||
Provider: tracing.DefaultProvider,
|
||||
Propagator: tracing.DefaultPropagator,
|
||||
}
|
||||
}
|
||||
|
||||
// Middleware returns a gRPC server middleware that creates spans for incoming RPC calls.
|
||||
// It extracts trace context from request metadata, creates a server span, and records
|
||||
// errors at the appropriate log level. If the provider is a no-op, it returns a pass-through middleware.
|
||||
func (c Config) Middleware() grpc.Middleware {
|
||||
if tracing.IsNoop(c.Provider) {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
return next(ctx, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracer := c.Provider.Tracer(tracerName)
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
if md == nil {
|
||||
md = metadata.MD{}
|
||||
}
|
||||
spanName, _ := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md)
|
||||
if spanName == "" {
|
||||
return next(ctx, message)
|
||||
}
|
||||
|
||||
ctx = c.Propagator.Extract(ctx, grpc2.MetadataCarrier(md))
|
||||
|
||||
attributes := []attribute.KeyValue{
|
||||
tracing.RequestId.String(requestid.FromContext(ctx)),
|
||||
}
|
||||
opts := []trace.SpanStartOption{
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(attributes...),
|
||||
}
|
||||
|
||||
ctx, span := tracer.Start(ctx, spanName, opts...)
|
||||
defer span.End()
|
||||
|
||||
resp, err := next(ctx, message)
|
||||
|
||||
if err != nil {
|
||||
logLevel := logutil.LogLevelForError(err)
|
||||
if logLevel == log.ErrorLevel {
|
||||
span.RecordError(err)
|
||||
}
|
||||
}
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
}
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
# Package `grpct`
|
||||
|
||||
Пакет `grpct` предназначен для упрощения написания юнит- и интеграционных тестов gRPC-сервисов на базе `isp-kit`.
|
||||
|
||||
## Types
|
||||
|
||||
### MockServer
|
||||
|
||||
Структура `MockServer` представляет собой обёртку над gRPC-сервером, позволяющую удобно мокать отдельные endpoint'ы.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewMock(t *test.Test) (*MockServer, *client.Client)`
|
||||
|
||||
Создаёт `MockServer` и соответствующий gRPC-клиент. Полезно для юнит-тестов и простых сценариев мокирования.
|
||||
|
||||
#### `(m *MockServer) Mock(endpoint string, handler any) *MockServer`
|
||||
|
||||
Регистрирует указанный `handler` на переданный `endpoint` с использованием `endpoint.Wrapper`.
|
||||
|
||||
## Functions
|
||||
|
||||
### `TestServer(t *test.Test, service isp.BackendServiceServer) (*grpc.Server, *client.Client)`
|
||||
|
||||
Создаёт полноценный `grpc.Server` с переданным `BackendServiceServer` и возвращает его вместе с клиентом. Подходит для end-to-end тестов.
|
||||
|
||||
Автоматически управляет закрытием ресурсов (`Shutdown` сервера и `Close` клиента) по окончании теста.
|
||||
|
||||
## Usage
|
||||
|
||||
### Create mock gRPC server and mock handler
|
||||
|
||||
```go
|
||||
package mypkg_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpct"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
func TestExample(t *testing.T) {
|
||||
testCtx := test.New(t)
|
||||
mockSrv, cli := grpct.NewMock(testCtx)
|
||||
mockSrv.Mock("/example.Service/Method", handlerFn)
|
||||
|
||||
resp, err := cli.Invoke(testCtx.Context(), "/example.Service/Method", req, &reply)
|
||||
testCtx.Assert().NoError(err)
|
||||
testCtx.Assert().Equal(expected, reply)
|
||||
}
|
||||
```
|
||||
|
||||
### Create test gRPC server from implementation
|
||||
|
||||
```go
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpct"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
func TestRealService(t *testing.T) {
|
||||
testCtx := test.New(t)
|
||||
srv, cli := grpct.TestServer(testCtx, myServiceImpl)
|
||||
|
||||
resp, err := cli.Invoke(testCtx.Context(), "/my.Service/Endpoint", req, &reply)
|
||||
testCtx.Assert().NoError(err)
|
||||
testCtx.Assert().Equal(expected, reply)
|
||||
|
||||
_ = srv // используется для дополнительных проверок, если необходимо
|
||||
}
|
||||
```
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
// Package grpct provides test helpers for gRPC server and client operations.
|
||||
// It creates mock gRPC servers on random local ports for testing.
|
||||
package grpct
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
// MockServer provides a mock gRPC server for testing.
|
||||
// It allows registering handlers for specific endpoints.
|
||||
type MockServer struct {
|
||||
Wrapper endpoint.Wrapper
|
||||
srv *grpc.Server
|
||||
router *grpc.Mux
|
||||
}
|
||||
|
||||
// NewMock creates a new mock gRPC server and client pair.
|
||||
// The server listens on a random local port and is automatically
|
||||
// shut down when the test completes.
|
||||
func NewMock(t *test.Test) (*MockServer, *client.Client) {
|
||||
srv, cli := TestServer(t, grpc.NewMux())
|
||||
router := grpc.NewMux()
|
||||
srv.Upgrade(router)
|
||||
return &MockServer{
|
||||
Wrapper: endpoint.DefaultWrapper(t.Logger()),
|
||||
srv: srv,
|
||||
router: router,
|
||||
}, cli
|
||||
}
|
||||
|
||||
// Mock registers a handler for the specified endpoint.
|
||||
// Returns the MockServer for method chaining.
|
||||
func (m *MockServer) Mock(endpoint string, handler any) *MockServer {
|
||||
m.router.Handle(endpoint, m.Wrapper.Endpoint(handler))
|
||||
return m
|
||||
}
|
||||
|
||||
// TestServer creates and starts a gRPC server with the provided service,
|
||||
// returning both the server and a configured client. The server listens
|
||||
// on a random local port and is automatically shut down when the test completes.
|
||||
func TestServer(t *test.Test, service isp.BackendServiceServer) (*grpc.Server, *client.Client) {
|
||||
assert := t.Assert()
|
||||
|
||||
var lc net.ListenConfig
|
||||
listener, err := lc.Listen(t.T().Context(), "tcp", "127.0.0.1:")
|
||||
assert.NoError(err)
|
||||
srv := grpc.NewServer()
|
||||
cli, err := client.Default()
|
||||
assert.NoError(err)
|
||||
t.T().Cleanup(func() {
|
||||
err := cli.Close()
|
||||
assert.NoError(err)
|
||||
srv.Shutdown()
|
||||
})
|
||||
srv.Upgrade(service)
|
||||
go func() {
|
||||
err := srv.Serve(listener)
|
||||
assert.NoError(err)
|
||||
}()
|
||||
|
||||
cli.Upgrade([]string{listener.Addr().String()})
|
||||
return srv, cli
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
# Package `httpt`
|
||||
|
||||
Пакет `httpt` предназначен для упрощения написания HTTP-тестов (юнит- и интеграционных) с использованием клиента и сервера на базе `isp-kit`.
|
||||
|
||||
## Types
|
||||
|
||||
### MockServer
|
||||
|
||||
Структура `MockServer` представляет собой обёртку над HTTP-сервером, позволяющую удобно мокать отдельные endpoint'ы с использованием `endpoint.Wrapper` и роутера `router.Router`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewMock(t *test.Test) *MockServer`
|
||||
|
||||
Создаёт `MockServer`, автоматически запускает сервер и регистрирует его закрытие в `t.Cleanup`. Подходит для юнит-тестов с ручной маршрутизацией и моками.
|
||||
|
||||
#### `(m *MockServer) POST(path string, handler any) *MockServer`
|
||||
|
||||
Регистрирует POST-обработчик на указанный путь.
|
||||
|
||||
#### `(m *MockServer) GET(path string, handler any) *MockServer`
|
||||
|
||||
Регистрирует GET-обработчик на указанный путь.
|
||||
|
||||
#### `(m *MockServer) Mock(method string, path string, handler any) *MockServer`
|
||||
|
||||
Регистрирует обработчик на указанный путь и метод с использованием `Wrapper.Endpoint`.
|
||||
|
||||
#### `(m *MockServer) Client(opts ...httpcli.Option) *httpcli.Client`
|
||||
|
||||
Создаёт HTTP-клиент, настроенный на тестовый сервер.
|
||||
|
||||
#### `(m *MockServer) BaseURL() string`
|
||||
|
||||
Возвращает базовый URL тестового сервера.
|
||||
|
||||
## Functions
|
||||
|
||||
### `TestServer(t *test.Test, handler http.Handler, opts ...httpcli.Option) (*httptest.Server, *httpcli.Client)`
|
||||
|
||||
Создаёт `httptest.Server` с указанным HTTP-обработчиком и возвращает его вместе с клиентом `httpcli.Client`. Подходит для end-to-end тестов.
|
||||
|
||||
Автоматически управляет закрытием ресурсов (`srv.Close`) по окончании теста.
|
||||
|
||||
## Usage
|
||||
|
||||
### Example usage in test
|
||||
|
||||
```go
|
||||
package mypkg_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpt"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
func TestExample(t *testing.T) {
|
||||
testCtx := test.New(t)
|
||||
srv, cli := httpt.TestServer(testCtx, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("ok"))
|
||||
}))
|
||||
|
||||
resp, err := cli.Get("/")
|
||||
testCtx.Assert().NoError(err)
|
||||
testCtx.Assert().Equal(200, resp.StatusCode)
|
||||
testCtx.Assert().BodyEqual(resp, "ok")
|
||||
_ = srv // для дополнительных проверок, если нужно
|
||||
}
|
||||
```
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package httpt
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
// TestServer creates and starts an HTTP test server with the provided handler,
|
||||
// returning both the server and a configured client. The server listens on
|
||||
// a random local port and the client is pre-configured with the server's URL.
|
||||
func TestServer(t *test.Test, handler http.Handler, opts ...httpcli.Option) (*httptest.Server, *httpcli.Client) {
|
||||
srv := httptest.NewServer(handler)
|
||||
cli := httpclix.Default(opts...)
|
||||
cli.GlobalRequestConfig().BaseUrl = srv.URL
|
||||
return srv, cli
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
// Package httpt provides test helpers for HTTP server and client operations.
|
||||
// It creates mock HTTP servers on random local ports for testing.
|
||||
package httpt
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/httplog"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
)
|
||||
|
||||
// MockServer provides a mock HTTP server for testing.
|
||||
// It uses httptest.Server and allows registering handlers for specific
|
||||
// HTTP methods and paths.
|
||||
type MockServer struct {
|
||||
Wrapper endpoint.Wrapper
|
||||
srv *httptest.Server
|
||||
router *router.Router
|
||||
}
|
||||
|
||||
// NewMock creates a new mock HTTP server.
|
||||
// The server listens on a random local port and is automatically
|
||||
// shut down when the test completes.
|
||||
func NewMock(t *test.Test) *MockServer {
|
||||
router := router.New()
|
||||
srv := httptest.NewServer(router)
|
||||
t.T().Cleanup(func() {
|
||||
srv.Close()
|
||||
})
|
||||
wrapper := endpoint.DefaultWrapper(t.Logger(), httplog.Log(t.Logger(), true))
|
||||
return &MockServer{
|
||||
Wrapper: wrapper,
|
||||
srv: srv,
|
||||
router: router,
|
||||
}
|
||||
}
|
||||
|
||||
// Client creates a new HTTP client configured to send requests to the
|
||||
// mock server's base URL. Optional client configuration can be provided.
|
||||
func (m *MockServer) Client(opts ...httpcli.Option) *httpcli.Client {
|
||||
cli := httpcli.New(opts...)
|
||||
cli.GlobalRequestConfig().BaseUrl = m.BaseURL()
|
||||
return cli
|
||||
}
|
||||
|
||||
// BaseURL returns the base URL of the mock server.
|
||||
func (m *MockServer) BaseURL() string {
|
||||
return m.srv.URL
|
||||
}
|
||||
|
||||
// POST registers a handler for POST requests at the specified path.
|
||||
// Returns the MockServer for method chaining.
|
||||
func (m *MockServer) POST(path string, handler any) *MockServer {
|
||||
return m.Mock(http.MethodPost, path, handler)
|
||||
}
|
||||
|
||||
// GET registers a handler for GET requests at the specified path.
|
||||
// Returns the MockServer for method chaining.
|
||||
func (m *MockServer) GET(path string, handler any) *MockServer {
|
||||
return m.Mock(http.MethodGet, path, handler)
|
||||
}
|
||||
|
||||
// Mock registers a handler for the specified HTTP method and path.
|
||||
// Returns the MockServer for method chaining.
|
||||
func (m *MockServer) Mock(method string, path string, handler any) *MockServer {
|
||||
m.router.Handler(method, path, m.Wrapper.Endpoint(handler))
|
||||
return m
|
||||
}
|
||||
Reference in new issue
Block a user