2024-01-22 17:22:41: merge [master:56d3e06e49d7a75f142424293788a4f3b6245430];
This commit is contained in:
1 parent
7014f56cbb
commit
2b91caece0
60 files changed
+3558
No files matched your search
@@ -0,0 +1,5 @@
|
||||
package proxy
|
||||
|
||||
const (
|
||||
xAdminIdHeader = "x-admin-id"
|
||||
)
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
|
||||
"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/integration-system/isp-kit/requestid"
|
||||
"github.com/pkg/errors"
|
||||
_ "google.golang.org/genproto/googleapis/rpc/errdetails"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
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
|
||||
skipAuth bool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func NewGrpc(cli *client.Client, skipAuth bool, timeout time.Duration) Grpc {
|
||||
return Grpc{
|
||||
cli: cli,
|
||||
skipAuth: skipAuth,
|
||||
timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
func (p Grpc) Handle(ctx *request.Context) error {
|
||||
body, err := io.ReadAll(ctx.Request().Body)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "grpc: read body")
|
||||
}
|
||||
|
||||
md := metadata.MD{
|
||||
grpc.ProxyMethodNameHeader: {ctx.Endpoint()},
|
||||
grpc.RequestIdHeader: {requestid.FromContext(ctx.Context())},
|
||||
}
|
||||
if !p.skipAuth {
|
||||
authData, err := ctx.GetAuthData()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get auth data")
|
||||
}
|
||||
md[grpc.SystemIdHeader] = []string{strconv.Itoa(authData.SystemId)}
|
||||
md[grpc.DomainIdHeader] = []string{strconv.Itoa(authData.DomainId)}
|
||||
md[grpc.ServiceIdHeader] = []string{strconv.Itoa(authData.ServiceId)}
|
||||
md[grpc.ApplicationIdHeader] = []string{strconv.Itoa(authData.ApplicationId)}
|
||||
if ctx.IsAdminAuthenticated() {
|
||||
md[xAdminIdHeader] = []string{strconv.Itoa(ctx.AdminId())}
|
||||
}
|
||||
}
|
||||
requestContext := metadata.NewOutgoingContext(ctx.Context(), md)
|
||||
|
||||
requestContext, cancel := context.WithTimeout(requestContext, p.timeout)
|
||||
defer cancel()
|
||||
result, err := p.cli.BackendClient().Request(requestContext, &isp.Message{
|
||||
Body: &isp.Message_BytesBody{BytesBody: body},
|
||||
})
|
||||
if err != nil {
|
||||
return p.handleError(err, ctx.ResponseWriter())
|
||||
}
|
||||
|
||||
return p.writeResponse(http.StatusOK, result.GetBytesBody(), ctx.ResponseWriter())
|
||||
}
|
||||
|
||||
func (p Grpc) handleError(err error, w http.ResponseWriter) error {
|
||||
status, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return httperrors.New(
|
||||
http.StatusServiceUnavailable,
|
||||
"upstream is not available",
|
||||
errors.WithMessage(err, "grpc proxy"),
|
||||
)
|
||||
}
|
||||
|
||||
statusCode := p.codeToHttpStatus(status.Code())
|
||||
for _, detail := range status.Details() {
|
||||
switch typeOfDetail := detail.(type) {
|
||||
case *isp.Message:
|
||||
switch {
|
||||
case typeOfDetail.GetBytesBody() != nil:
|
||||
return p.writeResponse(statusCode, typeOfDetail.GetBytesBody(), w)
|
||||
case typeOfDetail.GetListBody() != nil:
|
||||
return p.writeProto(statusCode, typeOfDetail.GetListBody(), w)
|
||||
case typeOfDetail.GetStructBody() != nil:
|
||||
return p.writeProto(statusCode, typeOfDetail.GetStructBody(), w)
|
||||
}
|
||||
default:
|
||||
return p.writeProto(statusCode, typeOfDetail, w)
|
||||
}
|
||||
}
|
||||
|
||||
return httperrors.New(
|
||||
statusCode,
|
||||
status.Message(),
|
||||
status.Err(),
|
||||
)
|
||||
}
|
||||
|
||||
func (p Grpc) writeProto(statusCode int, proto interface{}, w http.ResponseWriter) error {
|
||||
data, err := json.Marshal(proto)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal grpc details to json")
|
||||
}
|
||||
return p.writeResponse(statusCode, data, w)
|
||||
}
|
||||
|
||||
func (p Grpc) writeResponse(statusCode int, data []byte, w http.ResponseWriter) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(statusCode)
|
||||
_, err := w.Write(data)
|
||||
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
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
|
||||
"github.com/integration-system/isp-kit/grpc"
|
||||
"github.com/integration-system/isp-kit/requestid"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/net/context"
|
||||
)
|
||||
|
||||
// nolint:gomnd
|
||||
var (
|
||||
httpTransport = &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: defaultTransportDialContext(&net.Dialer{
|
||||
Timeout: 3 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}),
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 512,
|
||||
MaxIdleConnsPerHost: 32,
|
||||
IdleConnTimeout: 60 * time.Second,
|
||||
TLSHandshakeTimeout: 5 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
}
|
||||
)
|
||||
|
||||
type HttpHostManager interface {
|
||||
Next() (string, error)
|
||||
}
|
||||
|
||||
type Http struct {
|
||||
hostManager HttpHostManager
|
||||
skipAuth bool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func NewHttp(hostManager HttpHostManager, skipAuth bool, timeout time.Duration) Http {
|
||||
return Http{
|
||||
hostManager: hostManager,
|
||||
skipAuth: skipAuth,
|
||||
timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
func (p Http) Handle(ctx *request.Context) error {
|
||||
host, err := p.hostManager.Next()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "http: next host")
|
||||
}
|
||||
|
||||
rawUrl := fmt.Sprintf("http://%s", host) // secure HTTP links are reset connection
|
||||
target, err := url.Parse(rawUrl)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "http: parse url")
|
||||
}
|
||||
|
||||
request := ctx.Request()
|
||||
request.URL.Path = ctx.Endpoint()
|
||||
err = setHttpHeaders(ctx, request.Header, p.skipAuth)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reverseProxy := httputil.NewSingleHostReverseProxy(target)
|
||||
reverseProxy.Transport = httpTransport
|
||||
var resultError error
|
||||
reverseProxy.ErrorHandler = func(writer http.ResponseWriter, request *http.Request, err error) {
|
||||
resultError = httperrors.New(
|
||||
http.StatusServiceUnavailable,
|
||||
"upstream is not available",
|
||||
errors.WithMessagef(err, "http proxy to %s", host),
|
||||
)
|
||||
}
|
||||
|
||||
context, cancel := context.WithTimeout(request.Context(), p.timeout)
|
||||
defer cancel()
|
||||
request = request.WithContext(context)
|
||||
reverseProxy.ServeHTTP(ctx.ResponseWriter(), request)
|
||||
|
||||
return resultError
|
||||
}
|
||||
|
||||
func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) error {
|
||||
header.Set(grpc.RequestIdHeader, requestid.FromContext(ctx.Context()))
|
||||
if !skipAuth {
|
||||
authData, err := ctx.GetAuthData()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "http: get auth data")
|
||||
}
|
||||
header.Set(grpc.SystemIdHeader, strconv.Itoa(authData.SystemId))
|
||||
header.Set(grpc.DomainIdHeader, strconv.Itoa(authData.DomainId))
|
||||
header.Set(grpc.ServiceIdHeader, strconv.Itoa(authData.ServiceId))
|
||||
header.Set(grpc.ApplicationIdHeader, strconv.Itoa(authData.ApplicationId))
|
||||
if ctx.IsAdminAuthenticated() {
|
||||
header.Set(xAdminIdHeader, strconv.Itoa(ctx.AdminId()))
|
||||
} else {
|
||||
header.Del(xAdminIdHeader)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
|
||||
return dialer.DialContext
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/tomakado/websocketproxy"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type Ws struct {
|
||||
hostManager HttpHostManager
|
||||
skipAuth bool
|
||||
}
|
||||
|
||||
func NewWs(hostManager HttpHostManager, skipAuth bool) Ws {
|
||||
return Ws{
|
||||
hostManager: hostManager,
|
||||
skipAuth: skipAuth,
|
||||
}
|
||||
}
|
||||
|
||||
//nolint:gomnd
|
||||
func (ws Ws) Handle(ctx *request.Context) error {
|
||||
host, err := ws.hostManager.Next()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "ws: next host")
|
||||
}
|
||||
|
||||
rawUrl := fmt.Sprintf("ws://%s", host)
|
||||
target, err := url.Parse(rawUrl)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "ws: parse url")
|
||||
}
|
||||
|
||||
request := ctx.Request()
|
||||
request.URL.Path = ctx.Endpoint()
|
||||
|
||||
var resultError error
|
||||
proxy := websocketproxy.NewProxy(target)
|
||||
proxy.Director = func(incoming *http.Request, out http.Header) {
|
||||
_ = setHttpHeaders(ctx, out, ws.skipAuth)
|
||||
}
|
||||
proxy.Upgrader = &websocket.Upgrader{
|
||||
HandshakeTimeout: 5 * time.Second,
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
WriteBufferPool: nil,
|
||||
Subprotocols: nil,
|
||||
Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) {
|
||||
resultError = httperrors.New(
|
||||
http.StatusServiceUnavailable,
|
||||
"upstream is not available",
|
||||
errors.WithMessagef(reason, "ws proxy to %s", host),
|
||||
)
|
||||
},
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true
|
||||
},
|
||||
EnableCompression: false,
|
||||
}
|
||||
|
||||
proxy.ServeHTTP(ctx.ResponseWriter(), ctx.Request())
|
||||
|
||||
return resultError
|
||||
}
|
||||
Reference in new issue
Block a user