249 lines
5.5 KiB
Go
249 lines
5.5 KiB
Go
// nolint:wrapcheck
|
|
package proxy
|
|
|
|
import (
|
|
"io"
|
|
"isp-router-service/domain"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/pkg/errors"
|
|
"github.com/txix-open/isp-kit/grpc"
|
|
"github.com/txix-open/isp-kit/grpc/client"
|
|
"github.com/txix-open/isp-kit/grpc/isp"
|
|
"github.com/txix-open/isp-kit/json"
|
|
"github.com/txix-open/isp-kit/requestid"
|
|
grpc2 "google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/metadata"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
// nolint:gochecknoinits
|
|
func init() {
|
|
for httpCode, grpcCode := range codeMap {
|
|
inverseCodeMap[grpcCode] = httpCode
|
|
}
|
|
}
|
|
|
|
// nolint:gochecknoglobals
|
|
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 grpcResponse struct {
|
|
StatusCode int
|
|
Body []byte
|
|
Headers metadata.MD
|
|
}
|
|
|
|
type Grpc struct {
|
|
cli *client.Client
|
|
}
|
|
|
|
func NewGrpc(cli *client.Client) Grpc {
|
|
return Grpc{
|
|
cli: cli,
|
|
}
|
|
}
|
|
|
|
func (p Grpc) PrepareEndpoint(endpoint string, proxyApiPrefix bool) string {
|
|
endpoint = strings.TrimPrefix(endpoint, "/")
|
|
if !proxyApiPrefix {
|
|
return endpoint
|
|
}
|
|
|
|
if strings.HasPrefix(endpoint, "api/") {
|
|
return endpoint
|
|
}
|
|
|
|
return "api/" + endpoint
|
|
}
|
|
|
|
func (p Grpc) Handle(ctx *domain.RequestContext) error {
|
|
body, err := io.ReadAll(ctx.Request().Body)
|
|
if err != nil {
|
|
return errors.WithMessage(err, "grpc: read body")
|
|
}
|
|
|
|
requestId := requestid.FromContext(ctx.Context())
|
|
|
|
md := httpHeadersToGrpcMetadata(ctx.Request().Header)
|
|
md.Set(grpc.ProxyMethodNameHeader, ctx.Endpoint())
|
|
|
|
requestContext := metadata.NewOutgoingContext(ctx.Context(), md)
|
|
|
|
var header metadata.MD
|
|
result, err := p.cli.BackendClient().Request(requestContext, &isp.Message{
|
|
Body: &isp.Message_BytesBody{BytesBody: body},
|
|
}, grpc2.Header(&header))
|
|
if err != nil {
|
|
resp, err := p.grpcError(err, ctx.Endpoint(), header)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return p.writeResponse(resp, requestId, ctx.ResponseWriter())
|
|
}
|
|
|
|
resp := grpcResponse{
|
|
StatusCode: http.StatusOK,
|
|
Body: result.GetBytesBody(),
|
|
Headers: header,
|
|
}
|
|
return p.writeResponse(resp, requestId, ctx.ResponseWriter())
|
|
}
|
|
|
|
func (p Grpc) Close() error {
|
|
return p.cli.Close()
|
|
}
|
|
|
|
func (p Grpc) grpcError(
|
|
err error,
|
|
endpoint string,
|
|
headers metadata.MD,
|
|
) (grpcResponse, error) {
|
|
st, ok := status.FromError(err)
|
|
if !ok {
|
|
return grpcResponse{}, domain.NewHttpError(
|
|
http.StatusServiceUnavailable,
|
|
"upstream is not available",
|
|
errors.WithMessage(err, "grpc proxy"),
|
|
)
|
|
}
|
|
|
|
statusCode := p.codeToHttpStatus(st.Code())
|
|
for _, detail := range st.Details() {
|
|
msg, ok := detail.(*isp.Message)
|
|
if !ok {
|
|
return p.protoResponse(statusCode, detail, headers)
|
|
}
|
|
|
|
switch {
|
|
case msg.GetBytesBody() != nil:
|
|
return grpcResponse{
|
|
StatusCode: statusCode,
|
|
Body: msg.GetBytesBody(),
|
|
Headers: headers,
|
|
}, nil
|
|
|
|
case msg.GetListBody() != nil:
|
|
return p.protoResponse(statusCode, msg.GetListBody(), headers)
|
|
|
|
case msg.GetStructBody() != nil:
|
|
return p.protoResponse(statusCode, msg.GetStructBody(), headers)
|
|
}
|
|
}
|
|
|
|
return grpcResponse{}, domain.NewHttpError(
|
|
statusCode,
|
|
st.Message(),
|
|
errors.WithMessagef(err, "proxy '%s'", endpoint),
|
|
)
|
|
}
|
|
|
|
func (p Grpc) protoResponse(
|
|
statusCode int,
|
|
proto any,
|
|
headers metadata.MD,
|
|
) (grpcResponse, error) {
|
|
data, err := json.Marshal(proto)
|
|
if err != nil {
|
|
return grpcResponse{}, errors.WithMessage(err, "marshal grpc details to json")
|
|
}
|
|
|
|
return grpcResponse{
|
|
StatusCode: statusCode,
|
|
Body: data,
|
|
Headers: headers,
|
|
}, nil
|
|
}
|
|
|
|
func (p Grpc) writeResponse(
|
|
resp grpcResponse,
|
|
requestId string,
|
|
w http.ResponseWriter,
|
|
) error {
|
|
for header, values := range resp.Headers {
|
|
header = grpcHeaderToHttp(header)
|
|
if header == "" {
|
|
continue
|
|
}
|
|
|
|
for _, value := range values {
|
|
w.Header().Add(header, value)
|
|
}
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
|
|
if requestId != "" {
|
|
w.Header().Set(requestid.Header, requestId)
|
|
}
|
|
|
|
w.WriteHeader(resp.StatusCode)
|
|
_, err := w.Write(resp.Body)
|
|
if err != nil {
|
|
return errors.WithMessage(err, "response write")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (p Grpc) codeToHttpStatus(code codes.Code) int {
|
|
s, ok := inverseCodeMap[code]
|
|
if !ok {
|
|
return http.StatusInternalServerError
|
|
}
|
|
|
|
return s
|
|
}
|
|
|
|
func httpHeadersToGrpcMetadata(h http.Header) metadata.MD {
|
|
md := metadata.MD{}
|
|
for header, values := range h {
|
|
header := httpHeaderToGrpc(header)
|
|
if strings.HasPrefix(header, "x-") {
|
|
md.Set(header, values...)
|
|
}
|
|
}
|
|
return md
|
|
}
|
|
|
|
func grpcHeaderToHttp(grpcHeader string) string {
|
|
switch grpcHeader {
|
|
case grpc.ContentEncodingHeader:
|
|
return "Content-Encoding"
|
|
case grpc.AcceptEncodingHeader:
|
|
return "Accept-Encoding"
|
|
default:
|
|
return ""
|
|
}
|
|
}
|
|
|
|
func httpHeaderToGrpc(httpHeader string) string {
|
|
switch httpHeader {
|
|
case "Content-Encoding":
|
|
return grpc.ContentEncodingHeader
|
|
case "Accept-Encoding":
|
|
return grpc.AcceptEncodingHeader
|
|
default:
|
|
return strings.ToLower(httpHeader)
|
|
}
|
|
}
|