MSP-8974 fix tests for http
This commit is contained in:
1 parent
fa8bc6c1b7
commit
3e707244dd
26 files changed
+289
-1313
No files matched your search
-148
@@ -1,148 +0,0 @@
|
||||
# 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
@@ -1,102 +0,0 @@
|
||||
# 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
@@ -1,149 +0,0 @@
|
||||
// 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/txix-open/isp-kit/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
@@ -1,115 +0,0 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/txix-open/isp-kit/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
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
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
@@ -1,9 +0,0 @@
|
||||
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"
|
||||
)
|
||||
-241
@@ -1,241 +0,0 @@
|
||||
// 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
@@ -1,23 +0,0 @@
|
||||
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
@@ -1,176 +0,0 @@
|
||||
// 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
@@ -1,71 +0,0 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/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
@@ -1,118 +0,0 @@
|
||||
// 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/txix-open/isp-kit/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