diff --git a/proxy/grpc.go b/proxy/grpc.go new file mode 100644 index 0000000..3e030dc --- /dev/null +++ b/proxy/grpc.go @@ -0,0 +1,160 @@ +package proxy + +import ( + "io/ioutil" + "net/http" + "strconv" + + "github.com/integration-system/isp-kit/grpc" + "github.com/integration-system/isp-kit/grpc/client" + "github.com/integration-system/isp-kit/grpc/isp" + "github.com/integration-system/isp-kit/json" + "github.com/pkg/errors" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/structpb" + "isp-gate-service/domain" + "isp-gate-service/middleware" +) + +const ( + adminIdHeader = "x-auth-admin" +) + +func init() { + for httpCode, grpcCode := range codeMap { + inverseCodeMap[grpcCode] = httpCode + } +} + +var ( + codeMap = map[int]codes.Code{ + http.StatusOK: codes.OK, + http.StatusRequestTimeout: codes.Canceled, + http.StatusBadRequest: codes.InvalidArgument, + http.StatusGatewayTimeout: codes.DeadlineExceeded, + http.StatusNotFound: codes.NotFound, + http.StatusConflict: codes.AlreadyExists, + http.StatusForbidden: codes.PermissionDenied, + http.StatusUnauthorized: codes.Unauthenticated, + http.StatusTooManyRequests: codes.ResourceExhausted, + http.StatusPreconditionFailed: codes.FailedPrecondition, + http.StatusNotImplemented: codes.Unimplemented, + http.StatusInternalServerError: codes.Internal, + http.StatusServiceUnavailable: codes.Unavailable, + } + inverseCodeMap = map[codes.Code]int{} +) + +type Grpc struct { + cli *client.Client +} + +func NewGrpc(cli *client.Client) Grpc { + return Grpc{ + cli: cli, + } +} + +func (p Grpc) Handle(ctx *middleware.Context) error { + body, err := ioutil.ReadAll(ctx.Request.Body) + if err != nil { + return errors.WithMessage(err, "read body") + } + + md := make(metadata.MD) + md[grpc.ProxyMethodNameHeader] = []string{ctx.Path} + md[grpc.ApplicationIdHeader] = []string{strconv.Itoa(ctx.AppId)} + md[adminIdHeader] = []string{strconv.Itoa(ctx.AdminId)} + requestContext := metadata.NewOutgoingContext(ctx.Request.Context(), md) + + cli := p.cli.BackendClient() + + var resultBody []byte + var resultStatus int + result, err := cli.Request(requestContext, &isp.Message{ + Body: &isp.Message_BytesBody{BytesBody: body}, + }) + if err != nil { + resultBody, resultStatus = p.convertRequestErrorToBodyWithStatus(err) + } else { + resultBody = result.GetBytesBody() + resultStatus = http.StatusOK + } + + ctx.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8") + ctx.ResponseWriter.WriteHeader(resultStatus) + _, err = ctx.ResponseWriter.Write(resultBody) + if err != nil { + return errors.WithMessage(err, "response write") + } + + return nil +} + +func (p Grpc) convertRequestErrorToBodyWithStatus(err error) ([]byte, int) { + s, ok := status.FromError(err) + if !ok { + return []byte(domain.ServiceIsNotAvailableErrorMessage), http.StatusServiceUnavailable + } + + details := s.Details() + response := make([]byte, 0) + for _, detail := range details { + switch typeOfDetail := detail.(type) { + case *structpb.Struct: + result, err := typeOfDetail.MarshalJSON() + if err != nil { + return []byte(domain.ServiceIsNotAvailableErrorMessage), http.StatusServiceUnavailable + } + response = result + case *isp.Message: + listBody := typeOfDetail.GetListBody() + if listBody != nil { + result, err := listBody.MarshalJSON() + if err != nil { + return []byte(domain.ServiceIsNotAvailableErrorMessage), http.StatusServiceUnavailable + } + response = result + + break + } + + result := typeOfDetail.GetBytesBody() + response = result + default: + result, err := json.Marshal(typeOfDetail) + if err != nil { + return []byte(domain.ServiceIsNotAvailableErrorMessage), http.StatusServiceUnavailable + } + response = result + } + + break + } + + if len(response) == 0 { + detail := domain.Error{ + ErrorMessage: s.Message(), + ErrorCode: s.Code().String(), + } + + result, err := json.Marshal(detail) + if err != nil { + return []byte(domain.ServiceIsNotAvailableErrorMessage), http.StatusServiceUnavailable + } + response = result + } + + return response, p.codeToHttpStatus(s.Code()) +} + +func (p Grpc) codeToHttpStatus(code codes.Code) int { + s, ok := inverseCodeMap[code] + if !ok { + return http.StatusInternalServerError + } + + return s +} diff --git a/proxy/grpc/client.go b/proxy/grpc/client.go deleted file mode 100644 index f7e63ee..0000000 --- a/proxy/grpc/client.go +++ /dev/null @@ -1,50 +0,0 @@ -package grpc - -import ( - "github.com/integration-system/isp-lib/v2/backend" - "github.com/integration-system/isp-lib/v2/structure" - "github.com/valyala/fasthttp" - "google.golang.org/grpc" - "isp-gate-service/conf" - "isp-gate-service/domain" - "isp-gate-service/proxy/grpc/handlers" -) - -type grpcProxy struct { - client *backend.RxGrpcClient - skipAuth bool - skipExistCheck bool -} - -func NewProxy(skipAuth, skipExistCheck bool) *grpcProxy { - return &grpcProxy{ - client: backend.NewRxGrpcClient( - backend.WithDialOptions( - grpc.WithInsecure(), - grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(int(conf.DefaultMaxResponseBodySize))), - grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(int(conf.DefaultMaxResponseBodySize))), - )), - skipAuth: skipAuth, - skipExistCheck: skipExistCheck, - } -} - -func (p *grpcProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse { - return handlers.Handler.Get(ctx).Complete(ctx, path, p.client) -} - -func (p *grpcProxy) Consumer(addr []structure.AddressConfiguration) bool { - return p.client.ReceiveAddressList(addr) -} - -func (p *grpcProxy) SkipAuth() bool { - return p.skipAuth -} - -func (p *grpcProxy) SkipExistCheck() bool { - return p.skipExistCheck -} - -func (p *grpcProxy) Close() { - _ = p.client.Close() -} diff --git a/proxy/grpc/handlers/common.go b/proxy/grpc/handlers/common.go deleted file mode 100644 index 8cbffe7..0000000 --- a/proxy/grpc/handlers/common.go +++ /dev/null @@ -1,110 +0,0 @@ -package handlers - -import ( - "bytes" - "net/http" - - structpb "github.com/golang/protobuf/ptypes/struct" - "github.com/integration-system/isp-lib/v2/backend" - "github.com/integration-system/isp-lib/v2/config" - http2 "github.com/integration-system/isp-lib/v2/http" - "github.com/integration-system/isp-lib/v2/isp" - "github.com/integration-system/isp-lib/v2/structure" - "github.com/integration-system/isp-lib/v2/utils" - log "github.com/integration-system/isp-log" - jsoniter "github.com/json-iterator/go" - "github.com/valyala/fasthttp" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" - "google.golang.org/protobuf/proto" - "isp-gate-service/conf" - "isp-gate-service/log_code" -) - -const ( - errorMsgInternal = "Internal server error" - metadataSize = 5 -) - -var json = jsoniter.ConfigFastest - -func convertError(err error) ([]byte, int) { - s, ok := status.FromError(err) - if !ok { - return []byte(utils.ServiceError), http.StatusServiceUnavailable - } - cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting - if cfg.EnableOriginalProtoErrors { - body, err := proto.Marshal(s.Proto()) - if err != nil { - return []byte(utils.ServiceError), http.StatusServiceUnavailable - } - return body, http2.CodeToHttpStatus(s.Code()) - } - - details := s.Details() - newDetails := make([]interface{}, len(details)) - for i, detail := range details { - switch typeOfDetail := detail.(type) { - case *structpb.Struct: - newDetails[i] = utils.ConvertGrpcStructToInterface( - &structpb.Value{Kind: &structpb.Value_StructValue{StructValue: typeOfDetail}}, - ) - case *isp.Message: - newDetails[i] = utils.ConvertGrpcStructToInterface( - backend.ResolveBody(typeOfDetail), - ) - default: - newDetails[i] = typeOfDetail - } - } - - var respBody interface{} - if cfg.ProxyGrpcErrorDetails && len(newDetails) > 0 { - respBody = newDetails[0] - } else { - respBody = structure.GrpcError{ErrorMessage: s.Message(), ErrorCode: s.Code().String(), Details: newDetails} - } - - errorData, err := json.Marshal(respBody) - if err != nil { - log.Warn(log_code.WarnConvertErrorDataMarshalResponse, err) - return []byte(utils.ServiceError), http.StatusServiceUnavailable - } - return errorData, http2.CodeToHttpStatus(s.Code()) -} - -func getResponse(msg *isp.Message, err error) ([]byte, int, error) { - if err != nil { - errorBody, errorStatus := convertError(err) - return errorBody, errorStatus, nil - } - - bytes := msg.GetBytesBody() - if bytes != nil { - return bytes, http.StatusOK, nil - } - result := backend.ResolveBody(msg) - data := utils.ConvertGrpcStructToInterface(result) - byteResponse, err := json.Marshal(data) - return byteResponse, http.StatusOK, err -} - -func logHandlerError(typeData, method string, err error) { - log.WithMetadata(map[string]interface{}{ - log_code.MdTypeData: typeData, - log_code.MdMethod: method, - }).Warn(log_code.WarnProxyGrpcHandler, err) -} - -func makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string) { - md := make(metadata.MD, metadataSize) - md[utils.ProxyMethodNameHeader] = []string{method} - r.VisitAll(func(key, v []byte) { - lowerHeader := bytes.ToLower(key) - if len(v) > 0 && bytes.HasPrefix(lowerHeader, []byte("x-")) { - md[string(lowerHeader)] = []string{string(v)} - } - }) - return md, method -} diff --git a/proxy/grpc/handlers/description.go b/proxy/grpc/handlers/description.go deleted file mode 100644 index 6995f9e..0000000 --- a/proxy/grpc/handlers/description.go +++ /dev/null @@ -1,23 +0,0 @@ -package handlers - -import ( - "github.com/integration-system/isp-lib/v2/backend" - "github.com/valyala/fasthttp" - "isp-gate-service/domain" - "isp-gate-service/utils" -) - -var Handler handlerHelper - -type ( - handlerHelper struct{} - - handler interface { - Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse - } -) - -func (h handlerHelper) Get(ctx *fasthttp.RequestCtx) handler { - ctx.Response.Header.SetContentTypeBytes(utils.JsonContentType) - return handleJson -} diff --git a/proxy/grpc/handlers/handle_json.go b/proxy/grpc/handlers/handle_json.go deleted file mode 100644 index 3508350..0000000 --- a/proxy/grpc/handlers/handle_json.go +++ /dev/null @@ -1,50 +0,0 @@ -package handlers - -import ( - "github.com/integration-system/isp-lib/v2/backend" - "github.com/integration-system/isp-lib/v2/config" - "github.com/integration-system/isp-lib/v2/isp" - "github.com/valyala/fasthttp" - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "isp-gate-service/conf" - "isp-gate-service/domain" - "isp-gate-service/log_code" - "isp-gate-service/utils" -) - -var handleJson handleJsonDesc - -type handleJsonDesc struct{} - -func (p handleJsonDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse { - body := c.Request.Body() - - md, methodName := makeMetadata(&c.Request.Header, method) - ctx := metadata.NewOutgoingContext(context.Background(), md) - grpcSetting := config.GetRemote().(*conf.RemoteConfig).GrpcSetting - ctx, cancel := context.WithTimeout(ctx, grpcSetting.GetSyncInvokeTimeout()) - defer cancel() - - cli := client.Conn() - - msg, invokerErr := cli.Request( - ctx, - &isp.Message{ - Body: &isp.Message_BytesBody{BytesBody: body}, - }, - ) - - if response, status, err := getResponse(msg, invokerErr); err == nil { - c.SetStatusCode(status) - c.SetContentTypeBytes(utils.JsonContentType) - c.Response.Header.SetContentLength(len(response)) - _, _ = c.Write(response) - return domain.Create().SetRequestBody(body).SetResponseBody(c.Response.Body()).SetError(invokerErr) - } else { - logHandlerError(log_code.TypeData.JsonContent, methodName, err) - utils.WriteError(c, errorMsgInternal, codes.Internal, nil) - return domain.Create().SetRequestBody(body).SetResponseBody(c.Response.Body()).SetError(err) - } -}