MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+148
@@ -0,0 +1,148 @@
|
||||
# Package `grpc`
|
||||
|
||||
Пакет `grpc` предоставляет инструменты для создания и управления gRPC-серверами, включая обработку аутентификации,
|
||||
маршрутизацию запросов и интеграцию с метаданными.
|
||||
Поддерживает гибкую настройку обработчиков, безопасное обновление сервисов и работу с заголовками.
|
||||
|
||||
## Types
|
||||
|
||||
### Server
|
||||
|
||||
gRPC-сервер с поддержкой динамического обновления обработчиков.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `DefaultServer(restOptions ...grpc.ServerOption) *Server`
|
||||
|
||||
Создать gRPC-сервер с настройками по умолчанию (максимальный размер сообщения 64 МБ).
|
||||
|
||||
#### `NewServer(opts ...grpc.ServerOption) *Server`
|
||||
|
||||
Создать кастомный сервер с указанными опциями gRPC.
|
||||
|
||||
#### `(s *Server) Upgrade(service isp.BackendServiceServer)`
|
||||
|
||||
Атомарно обновить обработчик сервиса без остановки сервера.
|
||||
|
||||
#### `(s *Server) ListenAndServe(address string) error`
|
||||
|
||||
Запустить сервер на указанном адресе.
|
||||
|
||||
#### `(s *Server) Serve(listener net.Listener) error`
|
||||
|
||||
Запустить сервер на существующем listener.
|
||||
|
||||
#### `(s *Server) Shutdown()`
|
||||
|
||||
Остановить сервер
|
||||
|
||||
### Mux
|
||||
|
||||
Мультиплексор для маршрутизации gRPC-запросов. Регистрирует обработчики по имени эндпоинта.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewMux() *Mux`
|
||||
|
||||
Создать новый мультиплексор.
|
||||
|
||||
#### `(m *Mux) Handle(endpoint string, handler HandlerFunc) *Mux`
|
||||
|
||||
Зарегистрировать обработчик для указанного эндпоинта.
|
||||
|
||||
#### `(m *Mux) Request(ctx context.Context, message *isp.Message) (*isp.Message, error)`
|
||||
|
||||
Обрабатывает входящий запрос, определяя эндпоинт через заголовок `ProxyMethodNameHeader`.
|
||||
|
||||
### AuthData
|
||||
|
||||
Структура для работы с метаданными аутентификации в gRPC-запросах.
|
||||
Оборачивает `metadata.MD` и предоставляет методы для извлечения идентификаторов из заголовков.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(i AuthData) SystemId() (int, error)`
|
||||
|
||||
Получить идентификатор системы из заголовка `x-system-identity`.
|
||||
|
||||
#### `(i AuthData) DomainId() (int, error)`
|
||||
|
||||
Получить идентификатор домена из заголовка `x-domain-identity`.
|
||||
|
||||
#### `(i AuthData) ServiceId() (int, error)`
|
||||
|
||||
Получить идентификатор сервиса из заголовка `x-service-identity`.
|
||||
|
||||
#### `(i AuthData) ApplicationId() (int, error)`
|
||||
|
||||
Получить идентификатор системы из заголовка `x-application-identity`.
|
||||
|
||||
#### `(i AuthData) ApplicationName() (int, error)`
|
||||
|
||||
Получить название системы из заголовка `x-application-name`.
|
||||
|
||||
#### `(i AuthData) UserId() (int, error)`
|
||||
|
||||
Получить идентификатор пользователя из заголовка `x-user-identity`.
|
||||
|
||||
#### `(i AuthData) DeviceId() (int, error)`
|
||||
|
||||
Получить идентификатор устройства из заголовка `x-device-identity`.
|
||||
|
||||
#### `(i AuthData) UserToken() (string, error)`
|
||||
|
||||
Получить токен пользователя из заголовка `x-user-token`.
|
||||
|
||||
#### `(i AuthData) DeviceToken() (string, error)`
|
||||
|
||||
Получить токен устройства из заголовка `x-device-token`.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `StringFromMd(key string, md metadata.MD) (string, error)`
|
||||
|
||||
Извлекает строковое значение из метаданных по ключу.
|
||||
|
||||
#### `IntFromMd(key string, md metadata.MD) (int, error)`
|
||||
|
||||
Извлекает целочисленное значение из метаданных по ключу.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
mux := grpc.NewMux()
|
||||
mux.Handle("/get_users", func(ctx context.Context, msg *isp.Message) (*isp.Message, error) {
|
||||
/* put here business logic */
|
||||
return new(isp.Message), nil
|
||||
})
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
# Package `apierrors`
|
||||
|
||||
Пакет `apierrors` предоставляет структурированный формат ошибок для gRPC-сервисов с поддержкой кодов ошибок, деталей,
|
||||
уровней логирования и интеграции с gRPC-статусами. Позволяет единообразно обрабатывать бизнес-ошибки и технические сбои.
|
||||
|
||||
## Types
|
||||
|
||||
### Error
|
||||
|
||||
Структура для представления ошибки API. Реализует интерфейс `error`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewInternalServiceError(err error) Error`
|
||||
|
||||
Создает ошибку для внутренних сбоев сервера. Возвращает ошибку с gRPC-статусом 13 (internal), бизнесовым кодом 900 и
|
||||
уровнем
|
||||
логирования error.
|
||||
|
||||
#### `NewBusinessError(errorCode int, errorMessage string, err error) Error`
|
||||
|
||||
Создает бизнес-ошибку (например, невалидные данные от клиента). Возвращает ошибку с gRPC-статусом 3 (invalid argument),
|
||||
указанным
|
||||
бизнесовым кодом и уровнем логирования warn.
|
||||
|
||||
#### `New(httpStatusCode int, errorCode int, errorMessage string, err error) Error`
|
||||
|
||||
Создает кастомную ошибку с полным контролем параметров.
|
||||
|
||||
#### `(e Error) Error() string`
|
||||
|
||||
Получить строковое представление ошибки.
|
||||
|
||||
#### `(e Error) GrpcStatusError() error`
|
||||
|
||||
Конвертирует ошибку в gRPC-сообщение с сериализованными деталями об ошибке в формате JSON.
|
||||
|
||||
#### `(e Error) WithDetails(details map[string]any) Error`
|
||||
|
||||
Добавить детали информации об ошибке.
|
||||
|
||||
#### `(e Error) WithLogLevel(level log.Level) Error`
|
||||
|
||||
Изменить уровень логирования ошибки.
|
||||
|
||||
#### `(e Error) LogLevel() log.Level`
|
||||
|
||||
Получить текущий уровень логирования ошибки
|
||||
|
||||
## Functions
|
||||
|
||||
#### `FromError(err error) *Error`
|
||||
|
||||
Извлекает структурированную бизнесовую ошибку из gRPC-сообщения спрятанного под интерфейс `error`.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrUserNotFoundCode = 700
|
||||
)
|
||||
|
||||
type userService interface {
|
||||
GetUserById(ctx context.Context, id string) (*User, error)
|
||||
}
|
||||
|
||||
type userController struct {
|
||||
svc userService
|
||||
}
|
||||
|
||||
func (c userController) GetUser(ctx context.Context, userId string) (*User, error) {
|
||||
result, err := c.svc.GetUserById(ctx, userId)
|
||||
switch {
|
||||
case errors.Is(err, ErrUserNotFound):
|
||||
/* user isn't found so we have to send back specific error code */
|
||||
return nil, apierrors.NewBusinessError(ErrUserNotFoundCode, ErrUserNotFound.Error(), err)
|
||||
case err != nil:
|
||||
/* got some internal error */
|
||||
return nil, apierrors.NewInternalServiceError(err)
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
// Package apierrors provides structured error handling for gRPC services.
|
||||
// It defines custom error types with business error codes, gRPC status codes,
|
||||
// and structured details for comprehensive error reporting.
|
||||
//
|
||||
// Errors can be converted to gRPC status errors with JSON-encoded details,
|
||||
// enabling rich error information to be transmitted across service boundaries.
|
||||
package apierrors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
// ErrCodeInternal is the default error code for internal service errors.
|
||||
ErrCodeInternal = 900
|
||||
)
|
||||
|
||||
// Error represents a structured error with business and gRPC status codes.
|
||||
// Includes optional details for field-specific errors and a configurable log level.
|
||||
// Implements the GrpcError interface for conversion to gRPC status errors.
|
||||
//
|
||||
// Fields:
|
||||
// - ErrorCode: Business-level error code (e.g., 400 for bad request)
|
||||
// - ErrorMessage: Human-readable error message
|
||||
// - Details: Optional map of field-specific error details
|
||||
// - grpcStatusCode: gRPC status code (e.g., codes.InvalidArgument)
|
||||
// - cause: Underlying error cause
|
||||
// - level: Log level for error logging
|
||||
type Error struct {
|
||||
ErrorCode int
|
||||
ErrorMessage string
|
||||
Details map[string]any `json:",omitempty"`
|
||||
|
||||
grpcStatusCode codes.Code
|
||||
cause error
|
||||
level log.Level
|
||||
}
|
||||
|
||||
// NewInternalServiceError creates a new internal service error.
|
||||
// Uses gRPC status code Internal and business error code 900.
|
||||
// Sets log level to Error.
|
||||
func NewInternalServiceError(err error) Error {
|
||||
return New(codes.Internal, ErrCodeInternal, "internal service error", err).WithLogLevel(log.ErrorLevel)
|
||||
}
|
||||
|
||||
// NewBusinessError creates a new business validation error.
|
||||
// Uses gRPC status code InvalidArgument and the specified error code.
|
||||
// Sets log level to Warn.
|
||||
func NewBusinessError(errorCode int, errorMessage string, err error) Error {
|
||||
return New(codes.InvalidArgument, errorCode, errorMessage, err).WithLogLevel(log.WarnLevel)
|
||||
}
|
||||
|
||||
// New creates a new Error with the specified parameters.
|
||||
// Sets default log level to Error.
|
||||
func New(
|
||||
grpcStatusCode codes.Code,
|
||||
errorCode int,
|
||||
errorMessage string,
|
||||
err error,
|
||||
) Error {
|
||||
return Error{
|
||||
ErrorCode: errorCode,
|
||||
ErrorMessage: errorMessage,
|
||||
grpcStatusCode: grpcStatusCode,
|
||||
cause: err,
|
||||
level: log.ErrorLevel,
|
||||
}
|
||||
}
|
||||
|
||||
// Error returns a string representation of the error.
|
||||
// Includes error code, message, and underlying cause.
|
||||
func (e Error) Error() string {
|
||||
return fmt.Sprintf("errorCode: %d, errorMessage: %s, cause: %v", e.ErrorCode, e.ErrorMessage, e.cause)
|
||||
}
|
||||
|
||||
// GrpcStatusError converts the Error to a gRPC status error.
|
||||
// Serializes the error to JSON and attaches it as gRPC status details.
|
||||
// Returns an error if JSON marshaling or status creation fails.
|
||||
func (e Error) GrpcStatusError() error {
|
||||
data, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal json")
|
||||
}
|
||||
|
||||
msg := &isp.Message{
|
||||
Body: &isp.Message_BytesBody{
|
||||
BytesBody: data,
|
||||
},
|
||||
}
|
||||
s, err := status.New(e.grpcStatusCode, e.ErrorMessage).WithDetails(msg)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "set status details")
|
||||
}
|
||||
return s.Err()
|
||||
}
|
||||
|
||||
// WithDetails sets the error details map.
|
||||
// Returns the Error for method chaining.
|
||||
func (e Error) WithDetails(details map[string]any) Error {
|
||||
e.Details = details
|
||||
return e
|
||||
}
|
||||
|
||||
// WithLogLevel sets the log level for this error.
|
||||
// Returns the Error for method chaining.
|
||||
func (e Error) WithLogLevel(level log.Level) Error {
|
||||
e.level = level
|
||||
return e
|
||||
}
|
||||
|
||||
// LogLevel returns the log level for this error.
|
||||
func (e Error) LogLevel() log.Level {
|
||||
return e.level
|
||||
}
|
||||
|
||||
// FromError extracts an Error from a gRPC status error.
|
||||
// Returns nil if the error is not a gRPC status error or if the details cannot be parsed.
|
||||
// Useful for checking if an error originated from a remote service.
|
||||
func FromError(err error) *Error {
|
||||
s, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, detail := range s.Details() {
|
||||
typedDetail, ok := detail.(*isp.Message)
|
||||
if ok {
|
||||
errData := Error{}
|
||||
err := json.Unmarshal(typedDetail.GetBytesBody(), &errData)
|
||||
// not an error
|
||||
if err != nil {
|
||||
return nil // nolint:nilerr
|
||||
}
|
||||
if errData.ErrorCode == 0 {
|
||||
return nil
|
||||
}
|
||||
return &errData
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
const (
|
||||
// ApplicationIdHeader is the metadata key for application identity.
|
||||
ApplicationIdHeader = "x-application-identity"
|
||||
// ApplicationNameHeader is the metadata key for application name.
|
||||
ApplicationNameHeader = "x-application-name"
|
||||
// UserIdHeader is the metadata key for user identity.
|
||||
UserIdHeader = "x-user-identity"
|
||||
// DeviceIdHeader is the metadata key for device identity.
|
||||
DeviceIdHeader = "x-device-identity"
|
||||
// ServiceIdHeader is the metadata key for service identity.
|
||||
ServiceIdHeader = "x-service-identity"
|
||||
// DomainIdHeader is the metadata key for domain identity.
|
||||
DomainIdHeader = "x-domain-identity"
|
||||
// SystemIdHeader is the metadata key for system identity.
|
||||
SystemIdHeader = "x-system-identity"
|
||||
// UserTokenHeader is the metadata key for user token.
|
||||
UserTokenHeader = "x-user-token"
|
||||
// DeviceTokenHeader is the metadata key for device token.
|
||||
DeviceTokenHeader = "x-device-token"
|
||||
)
|
||||
|
||||
// AuthData wraps metadata.MD to provide structured access to authentication
|
||||
// and authorization information from gRPC request metadata.
|
||||
// All methods return an error if the key is not found or cannot be parsed.
|
||||
type AuthData metadata.MD
|
||||
|
||||
// SystemId extracts the system identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) SystemId() (int, error) {
|
||||
return IntFromMd(SystemIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// DomainId extracts the domain identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) DomainId() (int, error) {
|
||||
return IntFromMd(DomainIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// ServiceId extracts the service identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) ServiceId() (int, error) {
|
||||
return IntFromMd(ServiceIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// ApplicationId extracts the application identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) ApplicationId() (int, error) {
|
||||
return IntFromMd(ApplicationIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// ApplicationName extracts the application name from metadata as a string.
|
||||
// Returns an error if the key is not found.
|
||||
func (i AuthData) ApplicationName() (string, error) {
|
||||
return StringFromMd(ApplicationNameHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// UserId extracts the user identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) UserId() (int, error) {
|
||||
return IntFromMd(UserIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// DeviceId extracts the device identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) DeviceId() (int, error) {
|
||||
return IntFromMd(DeviceIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// UserToken extracts the user token from metadata as a string.
|
||||
// Returns an error if the key is not found.
|
||||
func (i AuthData) UserToken() (string, error) {
|
||||
return StringFromMd(UserTokenHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// DeviceToken extracts the device token from metadata as a string.
|
||||
// Returns an error if the key is not found.
|
||||
func (i AuthData) DeviceToken() (string, error) {
|
||||
return StringFromMd(DeviceTokenHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// StringFromMd extracts a string value from metadata by key.
|
||||
// Returns an error if metadata is nil or the key is not found.
|
||||
func StringFromMd(key string, md metadata.MD) (string, error) {
|
||||
if md == nil {
|
||||
return "", errors.New("metadata is nil")
|
||||
}
|
||||
values := md[key]
|
||||
if len(values) == 0 {
|
||||
return "", errors.Errorf("'%s' is expected in metadata", key)
|
||||
}
|
||||
return values[0], nil
|
||||
}
|
||||
|
||||
// IntFromMd extracts an integer value from metadata by key.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func IntFromMd(key string, md metadata.MD) (int, error) {
|
||||
value, err := StringFromMd(key, md)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
intValue, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "parse '%s' to int", key)
|
||||
}
|
||||
return intValue, nil
|
||||
}
|
||||
+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
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// HandlerFunc defines the signature for gRPC request handlers.
|
||||
// Receives a context and message, returns a response message and optional error.
|
||||
type HandlerFunc func(ctx context.Context, message *isp.Message) (*isp.Message, error)
|
||||
|
||||
// Middleware wraps a HandlerFunc 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 HandlerFunc) HandlerFunc
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package grpc
|
||||
|
||||
const (
|
||||
// AcceptEncodingHeader is the metadata key for accept encoding.
|
||||
AcceptEncodingHeader = "x-accept-encoding"
|
||||
|
||||
// ContentEncodingHeader is the metadata key for content encoding.
|
||||
ContentEncodingHeader = "x-content-encoding"
|
||||
)
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
# 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
@@ -0,0 +1,124 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
|
||||
"github.com/pkg/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
@@ -0,0 +1,68 @@
|
||||
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
@@ -0,0 +1,69 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"unicode"
|
||||
|
||||
"github.com/pkg/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
@@ -0,0 +1,29 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"github.com/pkg/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
@@ -0,0 +1,51 @@
|
||||
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
@@ -0,0 +1,221 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"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
@@ -0,0 +1,37 @@
|
||||
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
@@ -0,0 +1,107 @@
|
||||
// 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...),
|
||||
}
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.31.0
|
||||
// protoc v3.21.12
|
||||
// source: backed_service.proto
|
||||
|
||||
package isp
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
structpb "google.golang.org/protobuf/types/known/structpb"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
// Types that are assignable to Body:
|
||||
//
|
||||
// *Message_StructBody
|
||||
// *Message_ListBody
|
||||
// *Message_NullBody
|
||||
// *Message_BytesBody
|
||||
Body isMessage_Body `protobuf_oneof:"body"`
|
||||
}
|
||||
|
||||
func (x *Message) Reset() {
|
||||
*x = Message{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_backed_service_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Message) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Message) ProtoMessage() {}
|
||||
|
||||
func (x *Message) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_backed_service_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Message.ProtoReflect.Descriptor instead.
|
||||
func (*Message) Descriptor() ([]byte, []int) {
|
||||
return file_backed_service_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (m *Message) GetBody() isMessage_Body {
|
||||
if m != nil {
|
||||
return m.Body
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Message) GetStructBody() *structpb.Struct {
|
||||
if x, ok := x.GetBody().(*Message_StructBody); ok {
|
||||
return x.StructBody
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Message) GetListBody() *structpb.ListValue {
|
||||
if x, ok := x.GetBody().(*Message_ListBody); ok {
|
||||
return x.ListBody
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Message) GetNullBody() structpb.NullValue {
|
||||
if x, ok := x.GetBody().(*Message_NullBody); ok {
|
||||
return x.NullBody
|
||||
}
|
||||
return structpb.NullValue(0)
|
||||
}
|
||||
|
||||
func (x *Message) GetBytesBody() []byte {
|
||||
if x, ok := x.GetBody().(*Message_BytesBody); ok {
|
||||
return x.BytesBody
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type isMessage_Body interface {
|
||||
isMessage_Body()
|
||||
}
|
||||
|
||||
type Message_StructBody struct {
|
||||
StructBody *structpb.Struct `protobuf:"bytes,1,opt,name=structBody,proto3,oneof"`
|
||||
}
|
||||
|
||||
type Message_ListBody struct {
|
||||
ListBody *structpb.ListValue `protobuf:"bytes,2,opt,name=listBody,proto3,oneof"`
|
||||
}
|
||||
|
||||
type Message_NullBody struct {
|
||||
NullBody structpb.NullValue `protobuf:"varint,3,opt,name=NullBody,proto3,enum=google.protobuf.NullValue,oneof"`
|
||||
}
|
||||
|
||||
type Message_BytesBody struct {
|
||||
BytesBody []byte `protobuf:"bytes,4,opt,name=BytesBody,proto3,oneof"`
|
||||
}
|
||||
|
||||
func (*Message_StructBody) isMessage_Body() {}
|
||||
|
||||
func (*Message_ListBody) isMessage_Body() {}
|
||||
|
||||
func (*Message_NullBody) isMessage_Body() {}
|
||||
|
||||
func (*Message_BytesBody) isMessage_Body() {}
|
||||
|
||||
var File_backed_service_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_backed_service_proto_rawDesc = []byte{
|
||||
0x0a, 0x14, 0x62, 0x61, 0x63, 0x6b, 0x65, 0x64, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65,
|
||||
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x03, 0x69, 0x73, 0x70, 0x1a, 0x1c, 0x67, 0x6f, 0x6f,
|
||||
0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72,
|
||||
0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xe0, 0x01, 0x0a, 0x07, 0x4d, 0x65,
|
||||
0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42,
|
||||
0x6f, 0x64, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67,
|
||||
0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75,
|
||||
0x63, 0x74, 0x48, 0x00, 0x52, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42, 0x6f, 0x64, 0x79,
|
||||
0x12, 0x38, 0x0a, 0x08, 0x6c, 0x69, 0x73, 0x74, 0x42, 0x6f, 0x64, 0x79, 0x18, 0x02, 0x20, 0x01,
|
||||
0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74,
|
||||
0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x48, 0x00,
|
||||
0x52, 0x08, 0x6c, 0x69, 0x73, 0x74, 0x42, 0x6f, 0x64, 0x79, 0x12, 0x38, 0x0a, 0x08, 0x4e, 0x75,
|
||||
0x6c, 0x6c, 0x42, 0x6f, 0x64, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x67,
|
||||
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4e,
|
||||
0x75, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x48, 0x00, 0x52, 0x08, 0x4e, 0x75, 0x6c, 0x6c,
|
||||
0x42, 0x6f, 0x64, 0x79, 0x12, 0x1e, 0x0a, 0x09, 0x42, 0x79, 0x74, 0x65, 0x73, 0x42, 0x6f, 0x64,
|
||||
0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x09, 0x42, 0x79, 0x74, 0x65, 0x73,
|
||||
0x42, 0x6f, 0x64, 0x79, 0x42, 0x06, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x32, 0x6c, 0x0a, 0x0e,
|
||||
0x42, 0x61, 0x63, 0x6b, 0x65, 0x6e, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x27,
|
||||
0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e,
|
||||
0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d, 0x65,
|
||||
0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x12, 0x31, 0x0a, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x65,
|
||||
0x73, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d,
|
||||
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d, 0x65, 0x73,
|
||||
0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x42, 0x07, 0x5a, 0x05, 0x2e, 0x3b,
|
||||
0x69, 0x73, 0x70, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_backed_service_proto_rawDescOnce sync.Once
|
||||
file_backed_service_proto_rawDescData = file_backed_service_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_backed_service_proto_rawDescGZIP() []byte {
|
||||
file_backed_service_proto_rawDescOnce.Do(func() {
|
||||
file_backed_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_backed_service_proto_rawDescData)
|
||||
})
|
||||
return file_backed_service_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_backed_service_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
|
||||
var file_backed_service_proto_goTypes = []interface{}{
|
||||
(*Message)(nil), // 0: isp.Message
|
||||
(*structpb.Struct)(nil), // 1: google.protobuf.Struct
|
||||
(*structpb.ListValue)(nil), // 2: google.protobuf.ListValue
|
||||
(structpb.NullValue)(0), // 3: google.protobuf.NullValue
|
||||
}
|
||||
var file_backed_service_proto_depIdxs = []int32{
|
||||
1, // 0: isp.Message.structBody:type_name -> google.protobuf.Struct
|
||||
2, // 1: isp.Message.listBody:type_name -> google.protobuf.ListValue
|
||||
3, // 2: isp.Message.NullBody:type_name -> google.protobuf.NullValue
|
||||
0, // 3: isp.BackendService.Request:input_type -> isp.Message
|
||||
0, // 4: isp.BackendService.RequestStream:input_type -> isp.Message
|
||||
0, // 5: isp.BackendService.Request:output_type -> isp.Message
|
||||
0, // 6: isp.BackendService.RequestStream:output_type -> isp.Message
|
||||
5, // [5:7] is the sub-list for method output_type
|
||||
3, // [3:5] is the sub-list for method input_type
|
||||
3, // [3:3] is the sub-list for extension type_name
|
||||
3, // [3:3] is the sub-list for extension extendee
|
||||
0, // [0:3] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_backed_service_proto_init() }
|
||||
func file_backed_service_proto_init() {
|
||||
if File_backed_service_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_backed_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Message); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
file_backed_service_proto_msgTypes[0].OneofWrappers = []interface{}{
|
||||
(*Message_StructBody)(nil),
|
||||
(*Message_ListBody)(nil),
|
||||
(*Message_NullBody)(nil),
|
||||
(*Message_BytesBody)(nil),
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_backed_service_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 1,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_backed_service_proto_goTypes,
|
||||
DependencyIndexes: file_backed_service_proto_depIdxs,
|
||||
MessageInfos: file_backed_service_proto_msgTypes,
|
||||
}.Build()
|
||||
File_backed_service_proto = out.File
|
||||
file_backed_service_proto_rawDesc = nil
|
||||
file_backed_service_proto_goTypes = nil
|
||||
file_backed_service_proto_depIdxs = nil
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
syntax = "proto3";
|
||||
package isp;
|
||||
// protoc --go_out=plugins=grpc:. *.proto
|
||||
|
||||
option go_package = ".;isp";
|
||||
|
||||
import "google/protobuf/struct.proto";
|
||||
|
||||
message Message {
|
||||
oneof body {
|
||||
google.protobuf.Struct structBody = 1;
|
||||
google.protobuf.ListValue listBody = 2;
|
||||
google.protobuf.NullValue NullBody = 3;
|
||||
bytes BytesBody = 4;
|
||||
}
|
||||
}
|
||||
|
||||
service BackendService {
|
||||
// ===== SYSTEM =====
|
||||
rpc Request (Message) returns (Message) {}
|
||||
|
||||
rpc RequestStream(stream Message) returns (stream Message) {}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.2.0
|
||||
// - protoc v3.21.12
|
||||
// source: backed_service.proto
|
||||
|
||||
package isp
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.32.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion7
|
||||
|
||||
// BackendServiceClient is the client API for BackendService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type BackendServiceClient interface {
|
||||
// ===== SYSTEM =====
|
||||
Request(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error)
|
||||
RequestStream(ctx context.Context, opts ...grpc.CallOption) (BackendService_RequestStreamClient, error)
|
||||
}
|
||||
|
||||
type backendServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewBackendServiceClient(cc grpc.ClientConnInterface) BackendServiceClient {
|
||||
return &backendServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *backendServiceClient) Request(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error) {
|
||||
out := new(Message)
|
||||
err := c.cc.Invoke(ctx, "/isp.BackendService/Request", in, out, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *backendServiceClient) RequestStream(ctx context.Context, opts ...grpc.CallOption) (BackendService_RequestStreamClient, error) {
|
||||
stream, err := c.cc.NewStream(ctx, &BackendService_ServiceDesc.Streams[0], "/isp.BackendService/RequestStream", opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &backendServiceRequestStreamClient{stream}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
type BackendService_RequestStreamClient interface {
|
||||
Send(*Message) error
|
||||
Recv() (*Message, error)
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
type backendServiceRequestStreamClient struct {
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamClient) Send(m *Message) error {
|
||||
return x.ClientStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamClient) Recv() (*Message, error) {
|
||||
m := new(Message)
|
||||
if err := x.ClientStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// BackendServiceServer is the server API for BackendService service.
|
||||
// All implementations must embed UnimplementedBackendServiceServer
|
||||
// for forward compatibility
|
||||
type BackendServiceServer interface {
|
||||
// ===== SYSTEM =====
|
||||
Request(context.Context, *Message) (*Message, error)
|
||||
RequestStream(BackendService_RequestStreamServer) error
|
||||
mustEmbedUnimplementedBackendServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedBackendServiceServer must be embedded to have forward compatible implementations.
|
||||
type UnimplementedBackendServiceServer struct {
|
||||
}
|
||||
|
||||
func (UnimplementedBackendServiceServer) Request(context.Context, *Message) (*Message, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Request not implemented")
|
||||
}
|
||||
func (UnimplementedBackendServiceServer) RequestStream(BackendService_RequestStreamServer) error {
|
||||
return status.Errorf(codes.Unimplemented, "method RequestStream not implemented")
|
||||
}
|
||||
func (UnimplementedBackendServiceServer) mustEmbedUnimplementedBackendServiceServer() {}
|
||||
|
||||
// UnsafeBackendServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to BackendServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeBackendServiceServer interface {
|
||||
mustEmbedUnimplementedBackendServiceServer()
|
||||
}
|
||||
|
||||
func RegisterBackendServiceServer(s grpc.ServiceRegistrar, srv BackendServiceServer) {
|
||||
s.RegisterService(&BackendService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _BackendService_Request_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(Message)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(BackendServiceServer).Request(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: "/isp.BackendService/Request",
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(BackendServiceServer).Request(ctx, req.(*Message))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _BackendService_RequestStream_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
return srv.(BackendServiceServer).RequestStream(&backendServiceRequestStreamServer{stream})
|
||||
}
|
||||
|
||||
type BackendService_RequestStreamServer interface {
|
||||
Send(*Message) error
|
||||
Recv() (*Message, error)
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
type backendServiceRequestStreamServer struct {
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamServer) Send(m *Message) error {
|
||||
return x.ServerStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamServer) Recv() (*Message, error) {
|
||||
m := new(Message)
|
||||
if err := x.ServerStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// BackendService_ServiceDesc is the grpc.ServiceDesc for BackendService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var BackendService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "isp.BackendService",
|
||||
HandlerType: (*BackendServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "Request",
|
||||
Handler: _BackendService_Request_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
StreamName: "RequestStream",
|
||||
Handler: _BackendService_RequestStream_Handler,
|
||||
ServerStreams: true,
|
||||
ClientStreams: true,
|
||||
},
|
||||
},
|
||||
Metadata: "backed_service.proto",
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
// ProxyMethodNameHeader is the metadata key used to specify the target endpoint.
|
||||
ProxyMethodNameHeader = "proxy_method_name"
|
||||
)
|
||||
|
||||
// Mux is a request router that dispatches gRPC requests to registered handlers based on endpoint name.
|
||||
// It extracts the endpoint from request metadata and invokes the corresponding HandlerFunc.
|
||||
// Mux implements the BackendServiceServer interface but does not support streaming RPCs.
|
||||
type Mux struct {
|
||||
isp.UnimplementedBackendServiceServer
|
||||
|
||||
unaryHandlers map[string]HandlerFunc
|
||||
}
|
||||
|
||||
// NewMux creates a new Mux with an empty handler registry.
|
||||
func NewMux() *Mux {
|
||||
return &Mux{
|
||||
unaryHandlers: make(map[string]HandlerFunc),
|
||||
}
|
||||
}
|
||||
|
||||
// Handle registers a HandlerFunc for the specified endpoint.
|
||||
// Panics if a handler is already registered for the endpoint.
|
||||
// Returns the Mux for method chaining.
|
||||
func (m *Mux) Handle(endpoint string, handler HandlerFunc) *Mux {
|
||||
_, ok := m.unaryHandlers[endpoint]
|
||||
if ok {
|
||||
panic(errors.Errorf("handler for endpoint %v is already provided", endpoint))
|
||||
}
|
||||
m.unaryHandlers[endpoint] = handler
|
||||
return m
|
||||
}
|
||||
|
||||
// Request handles unary gRPC requests by routing to the registered handler for the endpoint.
|
||||
// The endpoint is extracted from the ProxyMethodNameHeader in request metadata.
|
||||
// Returns an error if metadata is missing, endpoint is not found, or handler fails.
|
||||
func (m *Mux) Request(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")
|
||||
}
|
||||
endpoint, err := StringFromMd(ProxyMethodNameHeader, md)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handler, ok := m.unaryHandlers[endpoint]
|
||||
if !ok {
|
||||
return nil, status.Errorf(codes.NotFound, "handler not found for endpoint %s", endpoint)
|
||||
}
|
||||
ctx = log.ToContext(ctx, log.String("endpoint", endpoint))
|
||||
return handler(ctx, message)
|
||||
}
|
||||
|
||||
// RequestStream returns an unimplemented error for streaming RPCs.
|
||||
// Mux does not support streaming; use a custom implementation for streaming support.
|
||||
func (m *Mux) RequestStream(_ isp.BackendService_RequestStreamServer) error {
|
||||
return status.Errorf(codes.Unimplemented, "service does not support streaming RPC")
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
// Package grpc provides a gRPC server and client implementation for the ISP kit framework.
|
||||
// It enables building scalable microservices with support for hot-swappable handlers,
|
||||
// middleware integration, and structured authentication via metadata.
|
||||
//
|
||||
// The package supports both unary and streaming RPCs, with built-in features for
|
||||
// request/response logging, metrics collection, and distributed tracing.
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultMaxSizeByte defines the default maximum message size in bytes (64MB).
|
||||
DefaultMaxSizeByte = 64 * 1024 * 1024
|
||||
)
|
||||
|
||||
// service implements the BackendServiceServer interface with hot-swappable handler support.
|
||||
// It uses atomic.Value for thread-safe handler replacement without interrupting in-flight requests.
|
||||
type service struct {
|
||||
isp.UnimplementedBackendServiceServer
|
||||
|
||||
delegate atomic.Value
|
||||
}
|
||||
|
||||
// Request handles unary gRPC requests by delegating to the registered BackendServiceServer.
|
||||
// Returns an error if the handler is not initialized.
|
||||
func (s *service) Request(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
delegate, ok := s.delegate.Load().(isp.BackendServiceServer)
|
||||
if !ok {
|
||||
return nil, errors.New("handler is not initialized")
|
||||
}
|
||||
return delegate.Request(ctx, message)
|
||||
}
|
||||
|
||||
// RequestStream handles streaming gRPC requests by delegating to the registered BackendServiceServer.
|
||||
// Returns an error if the handler is not initialized.
|
||||
func (s *service) RequestStream(server isp.BackendService_RequestStreamServer) error {
|
||||
delegate, ok := s.delegate.Load().(isp.BackendServiceServer)
|
||||
if !ok {
|
||||
return errors.New("handler is not initialized")
|
||||
}
|
||||
return delegate.RequestStream(server)
|
||||
}
|
||||
|
||||
// Server wraps a gRPC server with hot-swappable handler support.
|
||||
// It provides a clean interface for starting, stopping, and upgrading gRPC services
|
||||
// without requiring server restart.
|
||||
type Server struct {
|
||||
server *grpc.Server
|
||||
service *service
|
||||
}
|
||||
|
||||
// DefaultServer creates a new Server with default configuration including 64MB message size limits.
|
||||
// Accepts additional grpc.ServerOption for further customization.
|
||||
// Thread-safe for concurrent use.
|
||||
func DefaultServer(restOptions ...grpc.ServerOption) *Server {
|
||||
opts := append([]grpc.ServerOption{
|
||||
grpc.MaxRecvMsgSize(DefaultMaxSizeByte),
|
||||
grpc.MaxSendMsgSize(DefaultMaxSizeByte),
|
||||
}, restOptions...)
|
||||
return NewServer(opts...)
|
||||
}
|
||||
|
||||
// NewServer creates a new Server with custom gRPC options.
|
||||
// Accepts variadic grpc.ServerOption for full configuration control.
|
||||
// Thread-safe for concurrent use.
|
||||
func NewServer(opts ...grpc.ServerOption) *Server {
|
||||
s := &Server{
|
||||
server: grpc.NewServer(opts...),
|
||||
service: &service{
|
||||
delegate: atomic.Value{},
|
||||
},
|
||||
}
|
||||
isp.RegisterBackendServiceServer(s.server, s.service)
|
||||
return s
|
||||
}
|
||||
|
||||
// Shutdown gracefully stops the server, waiting for in-flight requests to complete.
|
||||
// Thread-safe for concurrent use.
|
||||
func (s *Server) Shutdown() {
|
||||
s.server.GracefulStop()
|
||||
}
|
||||
|
||||
// Upgrade atomically replaces the backend service handler without interrupting in-flight requests.
|
||||
// This enables hot-reload of business logic without server restart.
|
||||
// Thread-safe for concurrent use.
|
||||
func (s *Server) Upgrade(service isp.BackendServiceServer) {
|
||||
s.service.delegate.Store(service)
|
||||
}
|
||||
|
||||
// ListenAndServe binds the server to the specified TCP address and starts serving.
|
||||
// Returns an error if binding fails or serving encounters a fatal error.
|
||||
func (s *Server) ListenAndServe(address string) error {
|
||||
var lc net.ListenConfig
|
||||
listener, err := lc.Listen(context.Background(), "tcp", address)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "listen: %s", address)
|
||||
}
|
||||
return s.Serve(listener)
|
||||
}
|
||||
|
||||
// Serve starts serving gRPC requests on the provided listener.
|
||||
// Blocks until the server is stopped or an error occurs.
|
||||
// Returns an error if serving encounters a fatal error.
|
||||
func (s *Server) Serve(listener net.Listener) error {
|
||||
err := s.server.Serve(listener)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "serve grpc")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user