MSP-8974 fix tests for http
This commit is contained in:
1 parent
82a5de3782
commit
7a36a09fa8
26 files changed
+281
-1305
No files matched your search
+115
@@ -0,0 +1,115 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// ApplicationIdHeader is the header key for application identity.
|
||||||
|
ApplicationIdHeader = "x-application-identity"
|
||||||
|
// ApplicationNameHeader is the header key for application name.
|
||||||
|
ApplicationNameHeader = "x-application-name"
|
||||||
|
// UserIdHeader is the header key for user identity.
|
||||||
|
UserIdHeader = "x-user-identity"
|
||||||
|
// DeviceIdHeader is the header key for device identity.
|
||||||
|
DeviceIdHeader = "x-device-identity"
|
||||||
|
// ServiceIdHeader is the header key for service identity.
|
||||||
|
ServiceIdHeader = "x-service-identity"
|
||||||
|
// DomainIdHeader is the header key for domain identity.
|
||||||
|
DomainIdHeader = "x-domain-identity"
|
||||||
|
// SystemIdHeader is the header key for system identity.
|
||||||
|
SystemIdHeader = "x-system-identity"
|
||||||
|
// UserTokenHeader is the header key for user token.
|
||||||
|
UserTokenHeader = "x-user-token"
|
||||||
|
// DeviceTokenHeader is the header key for device token.
|
||||||
|
DeviceTokenHeader = "x-device-token"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AuthData wraps http.Header to provide structured access to authentication
|
||||||
|
// and authorization information from http request header.
|
||||||
|
// All methods return an error if the key is not found or cannot be parsed.
|
||||||
|
type AuthData http.Header
|
||||||
|
|
||||||
|
// SystemId extracts the system identity from header 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 IntFromHeader(SystemIdHeader, http.Header(i))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DomainId extracts the domain identity from header 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 IntFromHeader(DomainIdHeader, http.Header(i))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServiceId extracts the service identity from header 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 IntFromHeader(ServiceIdHeader, http.Header(i))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplicationId extracts the application identity from header 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 IntFromHeader(ApplicationIdHeader, http.Header(i))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplicationName extracts the application name from header as a string.
|
||||||
|
// Returns an error if the key is not found.
|
||||||
|
func (i AuthData) ApplicationName() (string, error) {
|
||||||
|
return StringFromHeader(ApplicationNameHeader, http.Header(i))
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserId extracts the user identity from header 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 IntFromHeader(UserIdHeader, http.Header(i))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeviceId extracts the device identity from header 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 IntFromHeader(DeviceIdHeader, http.Header(i))
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserToken extracts the user token from header as a string.
|
||||||
|
// Returns an error if the key is not found.
|
||||||
|
func (i AuthData) UserToken() (string, error) {
|
||||||
|
return StringFromHeader(UserTokenHeader, http.Header(i))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeviceToken extracts the device token from header as a string.
|
||||||
|
// Returns an error if the key is not found.
|
||||||
|
func (i AuthData) DeviceToken() (string, error) {
|
||||||
|
return StringFromHeader(DeviceTokenHeader, http.Header(i))
|
||||||
|
}
|
||||||
|
|
||||||
|
// StringFromHeader extracts a string value from header by key.
|
||||||
|
// Returns an error if header is nil or the key is not found.
|
||||||
|
func StringFromHeader(key string, h http.Header) (string, error) {
|
||||||
|
if h == nil {
|
||||||
|
return "", errors.New("header is nil")
|
||||||
|
}
|
||||||
|
values := h.Values(key)
|
||||||
|
if len(values) == 0 {
|
||||||
|
return "", errors.Errorf("'%s' is expected in header", key)
|
||||||
|
}
|
||||||
|
return values[0], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IntFromHeader extracts an integer value from header by key.
|
||||||
|
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||||
|
func IntFromHeader(key string, h http.Header) (int, error) {
|
||||||
|
value, err := StringFromHeader(key, h)
|
||||||
|
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
|
||||||
|
}
|
||||||
+3
-3
@@ -2,12 +2,12 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"isp-admin-service/domain"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"github.com/txix-open/isp-kit/errors"
|
||||||
"google.golang.org/grpc/codes"
|
"github.com/txix-open/isp-kit/http/apierrors"
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type AuditService interface {
|
type AuditService interface {
|
||||||
@@ -80,7 +80,7 @@ func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error
|
|||||||
err := c.service.SetEvents(ctx, req)
|
err := c.service.SetEvents(ctx, req)
|
||||||
switch {
|
switch {
|
||||||
case errors.As(err, &domain.UnknownAuditEventError{}):
|
case errors.As(err, &domain.UnknownAuditEventError{}):
|
||||||
return status.Error(codes.InvalidArgument, err.Error())
|
return apierrors.New(http.StatusBadRequest, domain.UnknownAuditEventErrorCode, err.Error(), err)
|
||||||
default:
|
default:
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-17
@@ -2,16 +2,15 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"isp-admin-service/auth"
|
||||||
"isp-admin-service/domain"
|
"isp-admin-service/domain"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"github.com/txix-open/isp-kit/errors"
|
||||||
"github.com/txix-open/isp-kit/grpc"
|
"github.com/txix-open/isp-kit/http/apierrors"
|
||||||
"github.com/txix-open/isp-kit/log"
|
"github.com/txix-open/isp-kit/log"
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/metadata"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type authService interface {
|
type authService interface {
|
||||||
@@ -43,8 +42,8 @@ func NewAuth(authService authService, logger log.Logger) Auth {
|
|||||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /auth/logout [POST]
|
// @Router /auth/logout [POST]
|
||||||
func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
|
func (a Auth) Logout(ctx context.Context, r *http.Request) error {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -69,8 +68,8 @@ func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
|
|||||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /auth/logout_with_reason [POST]
|
// @Router /auth/logout_with_reason [POST]
|
||||||
func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logoutRequest domain.LogoutRequest) error {
|
func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -100,12 +99,12 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
|
|||||||
|
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrOauthAuthorization):
|
case errors.Is(err, domain.ErrOauthAuthorization):
|
||||||
return nil, status.Error(codes.InvalidArgument, "plain auth is not available")
|
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthAuthorizationCode, err.Error(), err)
|
||||||
case errors.Is(err, domain.ErrUnauthenticated):
|
case errors.Is(err, domain.ErrUnauthenticated):
|
||||||
a.logger.Error(ctx, err.Error())
|
a.logger.Error(ctx, err.Error())
|
||||||
return nil, status.Error(codes.Unauthenticated, "invalid credential")
|
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||||
case errors.Is(err, domain.ErrTooManyLoginRequests):
|
case errors.Is(err, domain.ErrTooManyLoginRequests):
|
||||||
return nil, status.Error(codes.ResourceExhausted, "too many requests")
|
return nil, apierrors.New(http.StatusTooManyRequests, domain.ErrTooManyLoginRequestsCode, err.Error(), err)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "login")
|
return nil, errors.WithMessage(err, "login")
|
||||||
default:
|
default:
|
||||||
@@ -130,9 +129,9 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque
|
|||||||
|
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrOauthIsMissed):
|
case errors.Is(err, domain.ErrOauthIsMissed):
|
||||||
return nil, status.Error(codes.FailedPrecondition, "oauth is not configured")
|
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthIsMissedCode, err.Error(), err)
|
||||||
case errors.Is(err, domain.ErrUnauthenticated):
|
case errors.Is(err, domain.ErrUnauthenticated):
|
||||||
return nil, status.Error(codes.Unauthenticated, "invalid code")
|
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "login with oauth")
|
return nil, errors.WithMessage(err, "login with oauth")
|
||||||
default:
|
default:
|
||||||
@@ -140,15 +139,15 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getAdminId(authData grpc.AuthData) (int64, error) {
|
func getAdminId(r *http.Request) (int64, error) {
|
||||||
token, err := grpc.StringFromMd(domain.AdminAuthIdHeader, metadata.MD(authData))
|
token, err := auth.StringFromHeader(domain.AdminAuthIdHeader, r.Header)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, status.Error(codes.InvalidArgument, err.Error())
|
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
adminId, err := strconv.Atoi(token)
|
adminId, err := strconv.Atoi(token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, status.Error(codes.InvalidArgument, "admin id is not a number")
|
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return int64(adminId), nil
|
return int64(adminId), nil
|
||||||
|
|||||||
+11
-12
@@ -2,13 +2,12 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"isp-admin-service/domain"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"github.com/txix-open/isp-kit/errors"
|
||||||
"github.com/txix-open/isp-kit/grpc"
|
"github.com/txix-open/isp-kit/http/apierrors"
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type roleService interface {
|
type roleService interface {
|
||||||
@@ -61,8 +60,8 @@ func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
|||||||
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /role/create [POST]
|
// @Router /role/create [POST]
|
||||||
func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain.CreateRoleRequest) (*domain.Role, error) {
|
func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -70,7 +69,7 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain
|
|||||||
role, err := u.roleService.Create(ctx, req, adminId)
|
role, err := u.roleService.Create(ctx, req, adminId)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrAlreadyExists):
|
case errors.Is(err, domain.ErrAlreadyExists):
|
||||||
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "create role")
|
return nil, errors.WithMessage(err, "create role")
|
||||||
default:
|
default:
|
||||||
@@ -91,8 +90,8 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain
|
|||||||
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /role/update [POST]
|
// @Router /role/update [POST]
|
||||||
func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain.UpdateRoleRequest) (*domain.Role, error) {
|
func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -100,9 +99,9 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain
|
|||||||
result, err := u.roleService.Update(ctx, req, adminId)
|
result, err := u.roleService.Update(ctx, req, adminId)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
return nil, status.Error(codes.NotFound, "role not found")
|
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||||
case errors.Is(err, domain.ErrAlreadyExists):
|
case errors.Is(err, domain.ErrAlreadyExists):
|
||||||
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "update role")
|
return nil, errors.WithMessage(err, "update role")
|
||||||
default:
|
default:
|
||||||
@@ -122,8 +121,8 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain
|
|||||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /role/delete [POST]
|
// @Router /role/delete [POST]
|
||||||
func (u Role) DeleteRole(ctx context.Context, authData grpc.AuthData, req domain.DeleteRoleRequest) error {
|
func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import (
|
|||||||
"isp-admin-service/domain"
|
"isp-admin-service/domain"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"github.com/txix-open/isp-kit/errors"
|
||||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
"github.com/txix-open/isp-kit/http/apierrors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type SecureService interface {
|
type SecureService interface {
|
||||||
|
|||||||
@@ -3,10 +3,10 @@ package controller
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"isp-admin-service/domain"
|
"isp-admin-service/domain"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"github.com/txix-open/isp-kit/errors"
|
||||||
"google.golang.org/grpc/codes"
|
"github.com/txix-open/isp-kit/http/apierrors"
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type UiSettingsService interface {
|
type UiSettingsService interface {
|
||||||
@@ -39,7 +39,7 @@ func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequ
|
|||||||
resp, err := c.service.OauthSettings(ctx, req)
|
resp, err := c.service.OauthSettings(ctx, req)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrUnknownClient):
|
case errors.Is(err, domain.ErrUnknownClient):
|
||||||
return nil, status.Error(codes.Unauthenticated, "invalid client name")
|
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnknownClientCode, err.Error(), err)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, err
|
return nil, err
|
||||||
default:
|
default:
|
||||||
|
|||||||
+21
-23
@@ -2,15 +2,13 @@ package controller
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
"github.com/txix-open/isp-kit/http/apierrors"
|
||||||
|
|
||||||
"isp-admin-service/domain"
|
"isp-admin-service/domain"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
"github.com/txix-open/isp-kit/errors"
|
||||||
"github.com/txix-open/isp-kit/grpc"
|
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type userService interface {
|
type userService interface {
|
||||||
@@ -47,8 +45,8 @@ func NewUser(userService userService) User {
|
|||||||
// @Failure 404 {object} domain.GrpcError "Пользователя не существует"
|
// @Failure 404 {object} domain.GrpcError "Пользователя не существует"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /user/get_profile [POST]
|
// @Router /user/get_profile [POST]
|
||||||
func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.AdminUserShort, error) {
|
func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -56,9 +54,9 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A
|
|||||||
profile, err := u.userService.GetProfileById(ctx, adminId)
|
profile, err := u.userService.GetProfileById(ctx, adminId)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrUnauthenticated):
|
case errors.Is(err, domain.ErrUnauthenticated):
|
||||||
return nil, status.Error(codes.Unauthenticated, "user is blocked")
|
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
return nil, status.Error(codes.NotFound, "user not found")
|
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "get profile")
|
return nil, errors.WithMessage(err, "get profile")
|
||||||
default:
|
default:
|
||||||
@@ -127,8 +125,8 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
|
|||||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /user/create_user [POST]
|
// @Router /user/create_user [POST]
|
||||||
func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain.CreateUserRequest) (*domain.User, error) {
|
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -136,7 +134,7 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain
|
|||||||
user, err := u.userService.CreateUser(ctx, req, adminId)
|
user, err := u.userService.CreateUser(ctx, req, adminId)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrAlreadyExists):
|
case errors.Is(err, domain.ErrAlreadyExists):
|
||||||
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "create user")
|
return nil, errors.WithMessage(err, "create user")
|
||||||
default:
|
default:
|
||||||
@@ -158,8 +156,8 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain
|
|||||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /user/update_user [POST]
|
// @Router /user/update_user [POST]
|
||||||
func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain.UpdateUserRequest) (*domain.User, error) {
|
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -167,11 +165,11 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain
|
|||||||
result, err := u.userService.UpdateUser(ctx, req, adminId)
|
result, err := u.userService.UpdateUser(ctx, req, adminId)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
return nil, status.Error(codes.NotFound, "user not found")
|
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||||
case errors.Is(err, domain.ErrInvalid):
|
case errors.Is(err, domain.ErrInvalid):
|
||||||
return nil, status.Error(codes.InvalidArgument, "user modification is not available")
|
return nil, apierrors.New(http.StatusBadRequest, domain.ErrInvalidCode, err.Error(), err)
|
||||||
case errors.Is(err, domain.ErrAlreadyExists):
|
case errors.Is(err, domain.ErrAlreadyExists):
|
||||||
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return nil, errors.WithMessage(err, "update user")
|
return nil, errors.WithMessage(err, "update user")
|
||||||
default:
|
default:
|
||||||
@@ -191,8 +189,8 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain
|
|||||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /user/delete_user [POST]
|
// @Router /user/delete_user [POST]
|
||||||
func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) {
|
func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -216,8 +214,8 @@ func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities
|
|||||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||||
// @Failure 500 {object} domain.GrpcError
|
// @Failure 500 {object} domain.GrpcError
|
||||||
// @Router /user/block_user [POST]
|
// @Router /user/block_user [POST]
|
||||||
func (u User) Block(ctx context.Context, authData grpc.AuthData, identities domain.IdRequest) error {
|
func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -254,8 +252,8 @@ func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain
|
|||||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||||
// @Failure 500 {object} apierrors.Error "внутренняя ошибка"
|
// @Failure 500 {object} apierrors.Error "внутренняя ошибка"
|
||||||
// @Router /user/change_password [POST]
|
// @Router /user/change_password [POST]
|
||||||
func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req domain.ChangePasswordRequest) error {
|
func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest, r *http.Request) error {
|
||||||
adminId, err := getAdminId(authData)
|
adminId, err := getAdminId(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -263,7 +261,7 @@ func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req do
|
|||||||
err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword)
|
err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, domain.ErrInvalidPassword):
|
case errors.Is(err, domain.ErrInvalidPassword):
|
||||||
return apierrors.NewBusinessError(domain.ErrCodeInvalidPassword, "invalid password", err)
|
return apierrors.New(http.StatusBadRequest, domain.ErrCodeInvalidPassword, err.Error(), err)
|
||||||
case err != nil:
|
case err != nil:
|
||||||
return apierrors.NewInternalServiceError(err)
|
return apierrors.NewInternalServiceError(err)
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -26,6 +26,19 @@ var (
|
|||||||
ErrUnknownClient = errors.New("unknown client")
|
ErrUnknownClient = errors.New("unknown client")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
UnknownAuditEventErrorCode = 1
|
||||||
|
ErrOauthAuthorizationCode = 2
|
||||||
|
ErrUnauthenticatedCode = 3
|
||||||
|
ErrTooManyLoginRequestsCode = 4
|
||||||
|
ErrOauthIsMissedCode = 5
|
||||||
|
ErrAlreadyExistsCode = 6
|
||||||
|
ErrNotFoundCode = 7
|
||||||
|
ErrUnknownClientCode = 8
|
||||||
|
ErrInvalidCode = 9
|
||||||
|
ErrInvalidPasswordCode = 10
|
||||||
|
)
|
||||||
|
|
||||||
type UnknownAuditEventError struct {
|
type UnknownAuditEventError struct {
|
||||||
Event string
|
Event string
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
package domain
|
|
||||||
|
|
||||||
type GrpcError struct {
|
|
||||||
ErrorMessage string `json:"errorMessage"`
|
|
||||||
ErrorCode string `json:"errorCode"`
|
|
||||||
Details []any `json:"details"`
|
|
||||||
}
|
|
||||||
@@ -12,7 +12,6 @@ require (
|
|||||||
github.com/txix-open/jsonschema v1.3.0
|
github.com/txix-open/jsonschema v1.3.0
|
||||||
golang.org/x/crypto v0.55.0
|
golang.org/x/crypto v0.55.0
|
||||||
golang.org/x/sync v0.22.0
|
golang.org/x/sync v0.22.0
|
||||||
google.golang.org/grpc v1.83.2
|
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -78,6 +77,7 @@ require (
|
|||||||
golang.org/x/text v0.41.0 // indirect
|
golang.org/x/text v0.41.0 // indirect
|
||||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect
|
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect
|
||||||
|
google.golang.org/grpc v1.83.2 // indirect
|
||||||
google.golang.org/protobuf v1.36.12 // indirect
|
google.golang.org/protobuf v1.36.12 // indirect
|
||||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
|||||||
+7
-5
@@ -1,6 +1,7 @@
|
|||||||
package tests_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -16,8 +17,6 @@ import (
|
|||||||
"github.com/txix-open/isp-kit/test"
|
"github.com/txix-open/isp-kit/test"
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
"github.com/txix-open/isp-kit/test/httpt"
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAuditSuite(t *testing.T) {
|
func TestAuditSuite(t *testing.T) {
|
||||||
@@ -173,11 +172,14 @@ func (s *AuditSuite) Test_SetEvents_InvalidEvent() {
|
|||||||
{Event: entity.EventUserChanged, Enabled: true},
|
{Event: entity.EventUserChanged, Enabled: true},
|
||||||
{Event: "новый#2", Enabled: false},
|
{Event: "новый#2", Enabled: false},
|
||||||
}).
|
}).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
status, isStatus := status.FromError(err)
|
|
||||||
s.Require().True(isStatus)
|
var httpErr httpcli.ErrorResponse
|
||||||
s.Require().Equal(codes.InvalidArgument, status.Code())
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode) // не уверен тут какой код проверять? Статус или внутренний? Коммент чтобы не забыть
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuditSuite) Test_All_Logs() {
|
func (s *AuditSuite) Test_All_Logs() {
|
||||||
|
|||||||
+27
-17
@@ -27,8 +27,6 @@ import (
|
|||||||
"github.com/txix-open/isp-kit/json"
|
"github.com/txix-open/isp-kit/json"
|
||||||
"github.com/txix-open/isp-kit/test"
|
"github.com/txix-open/isp-kit/test"
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestAuthTestSuite(t *testing.T) {
|
func TestAuthTestSuite(t *testing.T) {
|
||||||
@@ -119,11 +117,13 @@ func (s *AuthTestSuite) TestLoginNotFound() {
|
|||||||
Email: "a1@a.ru",
|
Email: "a1@a.ru",
|
||||||
Password: "password",
|
Password: "password",
|
||||||
}).
|
}).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
st, ok := status.FromError(err)
|
|
||||||
s.Require().True(ok)
|
var httpErr httpcli.ErrorResponse
|
||||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||||
}
|
}
|
||||||
@@ -142,11 +142,13 @@ func (s *AuthTestSuite) TestBlockedUser() {
|
|||||||
Email: "a@a.ru",
|
Email: "a@a.ru",
|
||||||
Password: "password",
|
Password: "password",
|
||||||
}).
|
}).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
st, ok := status.FromError(err)
|
|
||||||
s.Require().True(ok)
|
var httpErr httpcli.ErrorResponse
|
||||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||||
}
|
}
|
||||||
@@ -164,11 +166,13 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
|
|||||||
Email: "a@a.ru",
|
Email: "a@a.ru",
|
||||||
Password: "WrongPassword",
|
Password: "WrongPassword",
|
||||||
}).
|
}).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
st, ok := status.FromError(err)
|
|
||||||
s.Require().True(ok)
|
var httpErr httpcli.ErrorResponse
|
||||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||||
|
|
||||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||||
}
|
}
|
||||||
@@ -204,11 +208,13 @@ func (s *AuthTestSuite) TestOauthLogin_UnknownClient() {
|
|||||||
ClientName: s.oauthClientName + fake.It[string](),
|
ClientName: s.oauthClientName + fake.It[string](),
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
st, ok := status.FromError(err)
|
|
||||||
s.Require().True(ok)
|
var httpErr httpcli.ErrorResponse
|
||||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||||
@@ -297,14 +303,18 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
|
|||||||
Password: fmt.Sprintf("password %s", strconv.Itoa(index)),
|
Password: fmt.Sprintf("password %s", strconv.Itoa(index)),
|
||||||
}).
|
}).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(ctx)
|
DoWithoutResponse(ctx)
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
|
|
||||||
switch status.Code(err) { // nolint:exhaustive
|
var httpErr httpcli.ErrorResponse
|
||||||
case codes.ResourceExhausted:
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
|
||||||
|
switch httpErr.StatusCode { // nolint:exhaustive
|
||||||
|
case http.StatusTooManyRequests:
|
||||||
tooManyRequestsErrorCount.Add(1)
|
tooManyRequestsErrorCount.Add(1)
|
||||||
s.Require().True(time.Since(start) < time.Second)
|
s.Require().True(time.Since(start) < time.Second)
|
||||||
case codes.Unauthenticated:
|
case http.StatusUnauthorized:
|
||||||
unauthorizedErrorCount.Add(1)
|
unauthorizedErrorCount.Add(1)
|
||||||
s.Require().True(time.Since(start) > time.Second)
|
s.Require().True(time.Since(start) > time.Second)
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"isp-admin-service/assembly"
|
"isp-admin-service/assembly"
|
||||||
"isp-admin-service/conf"
|
"isp-admin-service/conf"
|
||||||
"isp-admin-service/domain"
|
"isp-admin-service/domain"
|
||||||
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -12,8 +13,6 @@ import (
|
|||||||
"github.com/txix-open/isp-kit/test"
|
"github.com/txix-open/isp-kit/test"
|
||||||
"github.com/txix-open/isp-kit/test/fake"
|
"github.com/txix-open/isp-kit/test/fake"
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
"github.com/txix-open/isp-kit/test/httpt"
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type UiSettingsSuite struct {
|
type UiSettingsSuite struct {
|
||||||
@@ -97,9 +96,11 @@ func (s *UiSettingsSuite) Test_UnknownClient() {
|
|||||||
JsonRequestBody(domain.ClientNameRequest{
|
JsonRequestBody(domain.ClientNameRequest{
|
||||||
ClientName: s.oauthClientSetting.ClientName + fake.It[string](),
|
ClientName: s.oauthClientSetting.ClientName + fake.It[string](),
|
||||||
}).
|
}).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
st, ok := status.FromError(err)
|
|
||||||
s.Require().True(ok)
|
var httpErr httpcli.ErrorResponse
|
||||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||||
}
|
}
|
||||||
+57
-40
@@ -2,11 +2,12 @@ package tests_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
|
||||||
"isp-admin-service/assembly"
|
"isp-admin-service/assembly"
|
||||||
@@ -23,8 +24,6 @@ import (
|
|||||||
"github.com/txix-open/isp-kit/test"
|
"github.com/txix-open/isp-kit/test"
|
||||||
"github.com/txix-open/isp-kit/test/dbt"
|
"github.com/txix-open/isp-kit/test/dbt"
|
||||||
"github.com/txix-open/isp-kit/test/httpt"
|
"github.com/txix-open/isp-kit/test/httpt"
|
||||||
"google.golang.org/grpc/codes"
|
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type tokenService interface {
|
type tokenService interface {
|
||||||
@@ -89,7 +88,7 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
response := domain.AdminUserShort{}
|
response := domain.AdminUserShort{}
|
||||||
err := s.httpCli.Post("admin/user/get_profile").
|
err := s.apiCli.Post("admin/user/get_profile").
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
@@ -116,13 +115,14 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
|
|||||||
Password: "password",
|
Password: "password",
|
||||||
})
|
})
|
||||||
|
|
||||||
err := s.httpCli.Post("admin/user/get_profile").
|
err := s.apiCli.Post("admin/user/get_profile").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
st, ok := status.FromError(err)
|
var httpErr httpcli.ErrorResponse
|
||||||
s.Require().True(ok)
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
s.Require().Equal(codes.NotFound, st.Code())
|
s.Require().Equal(http.StatusNotFound, httpErr.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserTestSuite) TestGetProfileOauth() {
|
func (s *UserTestSuite) TestGetProfileOauth() {
|
||||||
@@ -144,7 +144,7 @@ func (s *UserTestSuite) TestGetProfileOauth() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
response := domain.AdminUserShort{}
|
response := domain.AdminUserShort{}
|
||||||
err := s.httpCli.
|
err := s.apiCli.
|
||||||
Post("admin/user/get_profile").
|
Post("admin/user/get_profile").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
@@ -183,7 +183,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
|||||||
email := "a1@"
|
email := "a1@"
|
||||||
|
|
||||||
response := domain.UsersResponse{}
|
response := domain.UsersResponse{}
|
||||||
err := s.httpCli.Post("admin/user/get_users").
|
err := s.apiCli.Post("admin/user/get_users").
|
||||||
JsonRequestBody(domain.UsersPageRequest{
|
JsonRequestBody(domain.UsersPageRequest{
|
||||||
LimitOffsetParams: domain.LimitOffsetParams{
|
LimitOffsetParams: domain.LimitOffsetParams{
|
||||||
Limit: 5,
|
Limit: 5,
|
||||||
@@ -211,7 +211,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
|||||||
s.Require().EqualValues(roles, response.Items[1].Roles)
|
s.Require().EqualValues(roles, response.Items[1].Roles)
|
||||||
|
|
||||||
email = "test@mail.ru"
|
email = "test@mail.ru"
|
||||||
err = s.httpCli.Post("admin/user/get_users").
|
err = s.apiCli.Post("admin/user/get_users").
|
||||||
JsonRequestBody(domain.UsersPageRequest{
|
JsonRequestBody(domain.UsersPageRequest{
|
||||||
LimitOffsetParams: domain.LimitOffsetParams{
|
LimitOffsetParams: domain.LimitOffsetParams{
|
||||||
Limit: 10,
|
Limit: 10,
|
||||||
@@ -250,7 +250,10 @@ func (s *UserTestSuite) TestAllGetUsers() {
|
|||||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)})
|
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)})
|
||||||
|
|
||||||
response := domain.UsersResponse{}
|
response := domain.UsersResponse{}
|
||||||
err := s.httpCli.Post("admin/user/get_all_users").JsonResponseBody(&response).DoWithoutResponse(s.T().Context())
|
err := s.apiCli.Post("admin/user/get_all_users").
|
||||||
|
JsonResponseBody(&response).
|
||||||
|
StatusCodeToError().
|
||||||
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|
||||||
s.Require().Len(response.Items, 7)
|
s.Require().Len(response.Items, 7)
|
||||||
@@ -295,7 +298,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
response := domain.UsersResponse{}
|
response := domain.UsersResponse{}
|
||||||
err = s.httpCli.Post("admin/user/get_users").
|
err = s.apiCli.Post("admin/user/get_users").
|
||||||
JsonRequestBody(domain.UsersPageRequest{
|
JsonRequestBody(domain.UsersPageRequest{
|
||||||
LimitOffsetParams: domain.LimitOffsetParams{
|
LimitOffsetParams: domain.LimitOffsetParams{
|
||||||
Limit: 5,
|
Limit: 5,
|
||||||
@@ -331,7 +334,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
|
|||||||
userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"})
|
userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"})
|
||||||
|
|
||||||
response := domain.UsersResponse{}
|
response := domain.UsersResponse{}
|
||||||
err := s.httpCli.Post("admin/user/get_users").
|
err := s.apiCli.Post("admin/user/get_users").
|
||||||
JsonRequestBody(domain.UsersPageRequest{
|
JsonRequestBody(domain.UsersPageRequest{
|
||||||
LimitOffsetParams: domain.LimitOffsetParams{
|
LimitOffsetParams: domain.LimitOffsetParams{
|
||||||
Limit: 10,
|
Limit: 10,
|
||||||
@@ -363,7 +366,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
|||||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||||
|
|
||||||
response := entity.User{}
|
response := entity.User{}
|
||||||
err := s.httpCli.
|
err := s.apiCli.
|
||||||
Post("admin/user/create_user").
|
Post("admin/user/create_user").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||||
JsonRequestBody(domain.CreateUserRequest{
|
JsonRequestBody(domain.CreateUserRequest{
|
||||||
@@ -391,7 +394,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
|||||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||||
|
|
||||||
response := entity.User{}
|
response := entity.User{}
|
||||||
err := s.httpCli.
|
err := s.apiCli.
|
||||||
Post("admin/user/create_user").
|
Post("admin/user/create_user").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||||
JsonRequestBody(domain.CreateUserRequest{
|
JsonRequestBody(domain.CreateUserRequest{
|
||||||
@@ -414,7 +417,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
|||||||
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||||
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
|
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
|
||||||
|
|
||||||
err := s.httpCli.
|
err := s.apiCli.
|
||||||
Post("admin/user/create_user").
|
Post("admin/user/create_user").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
JsonRequestBody(domain.CreateUserRequest{
|
JsonRequestBody(domain.CreateUserRequest{
|
||||||
@@ -423,11 +426,13 @@ func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
|||||||
Email: "exists@a.ru",
|
Email: "exists@a.ru",
|
||||||
Password: "password",
|
Password: "password",
|
||||||
}).
|
}).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
st, ok := status.FromError(err)
|
|
||||||
s.Require().True(ok)
|
var httpErr httpcli.ErrorResponse
|
||||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||||
@@ -439,8 +444,7 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
|||||||
Email: "update@a.ru",
|
Email: "update@a.ru",
|
||||||
}
|
}
|
||||||
response := domain.User{}
|
response := domain.User{}
|
||||||
err := s.httpCli.
|
err := s.httpCli.Post("admin/user/update_user").
|
||||||
Post("admin/user/update_user").
|
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
@@ -466,8 +470,7 @@ func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() {
|
|||||||
Email: "oauth@a.ru",
|
Email: "oauth@a.ru",
|
||||||
}
|
}
|
||||||
response := domain.User{}
|
response := domain.User{}
|
||||||
err := s.httpCli.
|
err := s.httpCli.Post("admin/user/update_user").
|
||||||
Post("admin/user/update_user").
|
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
JsonResponseBody(&response).
|
JsonResponseBody(&response).
|
||||||
@@ -494,15 +497,16 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
|||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
Email: "a_exists@a.ru",
|
Email: "a_exists@a.ru",
|
||||||
}
|
}
|
||||||
err := s.httpCli.
|
err := s.httpCli.Post("admin/user/update_user").
|
||||||
Post("admin/user/update_user").
|
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
st, ok := status.FromError(err)
|
|
||||||
s.Require().True(ok)
|
var httpErr httpcli.ErrorResponse
|
||||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
||||||
@@ -517,15 +521,16 @@ func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
|||||||
LastName: "surname",
|
LastName: "surname",
|
||||||
Email: "a_exists@a.ru",
|
Email: "a_exists@a.ru",
|
||||||
}
|
}
|
||||||
err := s.httpCli.
|
err := s.httpCli.Post("admin/user/update_user").
|
||||||
Post("admin/user/update_user").
|
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||||
JsonRequestBody(req).
|
JsonRequestBody(req).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
st, ok := status.FromError(err)
|
|
||||||
s.Require().True(ok)
|
var httpErr httpcli.ErrorResponse
|
||||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserTestSuite) TestDeleteUsers() {
|
func (s *UserTestSuite) TestDeleteUsers() {
|
||||||
@@ -535,7 +540,7 @@ func (s *UserTestSuite) TestDeleteUsers() {
|
|||||||
InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
|
InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
|
||||||
|
|
||||||
response := domain.DeleteResponse{}
|
response := domain.DeleteResponse{}
|
||||||
err := s.httpCli.
|
err := s.apiCli.
|
||||||
Post("admin/user/delete_user").
|
Post("admin/user/delete_user").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||||
JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}).
|
JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}).
|
||||||
@@ -566,8 +571,9 @@ func (s *UserTestSuite) TestBlockUser() {
|
|||||||
UpdatedAt: time.Now(),
|
UpdatedAt: time.Now(),
|
||||||
})
|
})
|
||||||
|
|
||||||
err := s.httpCli.Post("admin/user/block_user").
|
err := s.apiCli.Post("admin/user/block_user").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||||
|
StatusCodeToError().
|
||||||
JsonRequestBody(domain.IdRequest{UserId: int(id)}).
|
JsonRequestBody(domain.IdRequest{UserId: int(id)}).
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
@@ -597,19 +603,30 @@ func (s *UserTestSuite) TestChangePasswordUser() {
|
|||||||
|
|
||||||
// check for err when invalid data
|
// check for err when invalid data
|
||||||
invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"}
|
invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"}
|
||||||
err := s.httpCli.Post("admin/user/change_password").
|
err := s.apiCli.Post("admin/user/change_password").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||||
JsonRequestBody(invalidReq).
|
JsonRequestBody(invalidReq).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
s.Require().Error(err)
|
s.Require().Error(err)
|
||||||
err = apierrors.FromError(err)
|
|
||||||
s.Require().Contains(err.Error(), strconv.Itoa(domain.ErrCodeInvalidPassword))
|
var httpErr httpcli.ErrorResponse
|
||||||
|
s.Require().ErrorAs(err, &httpErr)
|
||||||
|
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
|
||||||
|
|
||||||
|
var body struct {
|
||||||
|
ErrorCode int `json:"errorCode"`
|
||||||
|
ErrorMessage string `json:"errorMessage"`
|
||||||
|
}
|
||||||
|
s.Require().NoError(json.Unmarshal(httpErr.Body, &body))
|
||||||
|
s.Require().Equal(domain.ErrCodeInvalidPassword, body.ErrorCode)
|
||||||
|
|
||||||
// change password
|
// change password
|
||||||
changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"}
|
changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"}
|
||||||
err = s.httpCli.Post("admin/user/change_password").
|
err = s.apiCli.Post("admin/user/change_password").
|
||||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||||
JsonRequestBody(changePswReq).
|
JsonRequestBody(changePswReq).
|
||||||
|
StatusCodeToError().
|
||||||
DoWithoutResponse(s.T().Context())
|
DoWithoutResponse(s.T().Context())
|
||||||
|
|
||||||
s.Require().NoError(err)
|
s.Require().NoError(err)
|
||||||
|
|||||||
-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
|
|
||||||
}
|
|
||||||
Vendored
-3
@@ -232,9 +232,6 @@ github.com/txix-open/isp-kit/dbrx
|
|||||||
github.com/txix-open/isp-kit/dbx
|
github.com/txix-open/isp-kit/dbx
|
||||||
github.com/txix-open/isp-kit/dbx/migration
|
github.com/txix-open/isp-kit/dbx/migration
|
||||||
github.com/txix-open/isp-kit/errors
|
github.com/txix-open/isp-kit/errors
|
||||||
github.com/txix-open/isp-kit/grpc
|
|
||||||
github.com/txix-open/isp-kit/grpc/apierrors
|
|
||||||
github.com/txix-open/isp-kit/grpc/isp
|
|
||||||
github.com/txix-open/isp-kit/healthcheck
|
github.com/txix-open/isp-kit/healthcheck
|
||||||
github.com/txix-open/isp-kit/http
|
github.com/txix-open/isp-kit/http
|
||||||
github.com/txix-open/isp-kit/http/apierrors
|
github.com/txix-open/isp-kit/http/apierrors
|
||||||
|
|||||||
Reference in new issue
Block a user