MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+112
@@ -0,0 +1,112 @@
|
||||
# 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 */
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
// 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"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
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 i := len(cli.middlewares) - 1; i >= 0; i-- {
|
||||
roundTripper = cli.middlewares[i](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
@@ -0,0 +1,39 @@
|
||||
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
@@ -0,0 +1,161 @@
|
||||
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
@@ -0,0 +1,86 @@
|
||||
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
@@ -0,0 +1,138 @@
|
||||
# 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
@@ -0,0 +1,159 @@
|
||||
// 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/pkg/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
@@ -0,0 +1,17 @@
|
||||
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
|
||||
Reference in new issue
Block a user