MSP-625 remove file handler

This commit is contained in:
DeniskaRediska authored and d1slike committed 2022-07-27 10:43:47 +03:00
1 parent 6f511ddc53
commit ad57079fc6
4 files changed
+2 -381

No files matched your search

+2 -57
View File
@@ -2,9 +2,7 @@ package handlers
import (
"bytes"
"io"
"net/http"
"time"
structpb "github.com/golang/protobuf/ptypes/struct"
"github.com/integration-system/isp-lib/v2/backend"
@@ -16,27 +14,16 @@ import (
log "github.com/integration-system/isp-log"
jsoniter "github.com/json-iterator/go"
"github.com/valyala/fasthttp"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
utils2 "isp-gate-service/utils"
)
const (
headerKeyContentDisposition = "Content-Disposition"
headerKeyContentType = "Content-Type"
headerKeyContentLength = "Content-Length"
headerKeyTransferEncoding = "Transfer-Encoding"
errorMsgInternal = "Internal server error"
errorMsgInvalidArg = "Not able to read request body"
metadataSize = 5
errorMsgInternal = "Internal server error"
metadataSize = 5
)
var json = jsoniter.ConfigFastest
@@ -110,19 +97,6 @@ func logHandlerError(typeData, method string, err error) {
}).Warn(log_code.WarnProxyGrpcHandler, err)
}
func openStream(headers *fasthttp.RequestHeader, method string, timeout time.Duration, client *backend.RxGrpcClient) (
isp.BackendService_RequestStreamClient, context.CancelFunc, error) {
cli := client.Conn()
md, _ := makeMetadata(headers, method)
ctx := metadata.NewOutgoingContext(context.Background(), md)
ctx, cancel := context.WithTimeout(ctx, timeout)
stream, err := cli.RequestStream(ctx)
if err != nil {
return nil, nil, err
}
return stream, cancel, nil
}
func makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string) {
md := make(metadata.MD, metadataSize)
md[utils.ProxyMethodNameHeader] = []string{method}
@@ -134,32 +108,3 @@ func makeMetadata(r *fasthttp.RequestHeader, method string) (metadata.MD, string
})
return md, method
}
func checkError(err error, ctx *fasthttp.RequestCtx, method string) (bool, bool, domain.ProxyResponse) {
var (
ok = true
eof = false
resp = domain.ProxyResponse{}
msg = errorMsgInternal
code = codes.Internal
details []interface{} = nil
)
if err != nil {
if err != io.EOF {
s, itStatus := status.FromError(err)
if itStatus {
msg = s.Message()
code = s.Code()
details = s.Details()
}
logHandlerError(log_code.TypeData.GetFile, method, err)
utils2.WriteError(ctx, msg, code, details)
resp = domain.Create().SetError(err)
ok, eof = false, false
} else {
ok, eof = true, true
}
}
return ok, eof, resp
}
-28
View File
@@ -2,11 +2,9 @@ package handlers
import (
"github.com/integration-system/isp-lib/v2/backend"
u "github.com/integration-system/isp-lib/v2/utils"
"github.com/valyala/fasthttp"
"isp-gate-service/domain"
"isp-gate-service/utils"
"mime"
)
var Handler handlerHelper
@@ -20,32 +18,6 @@ type (
)
func (h handlerHelper) Get(ctx *fasthttp.RequestCtx) handler {
isMultipart := h.isMultipart(ctx)
isExpectFile := string(ctx.Request.Header.Peek(u.ExpectFileHeader)) == "true"
if isMultipart {
ctx.Response.Header.SetContentTypeBytes(utils.JsonContentType)
return sendMultipartData
}
if isExpectFile {
return getFile
}
ctx.Response.Header.SetContentTypeBytes(utils.JsonContentType)
return handleJson
}
func (h handlerHelper) isMultipart(ctx *fasthttp.RequestCtx) bool {
if !ctx.IsPost() {
return false
}
v := string(ctx.Request.Header.ContentType())
if v == "" {
return false
}
d, params, err := mime.ParseMediaType(v)
if err != nil || d != "multipart/form-data" {
return false
}
_, ok := params["boundary"]
return ok
}
-138
View File
@@ -1,138 +0,0 @@
package handlers
import (
"fmt"
"github.com/integration-system/isp-lib/v2/backend"
"github.com/integration-system/isp-lib/v2/config"
"github.com/integration-system/isp-lib/v2/isp"
s "github.com/integration-system/isp-lib/v2/streaming"
u "github.com/integration-system/isp-lib/v2/utils"
log "github.com/integration-system/isp-log"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"io"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"strconv"
)
var (
errInvalidJson = errors.New("invalid json format. Expected object or array")
getFile getFileDesc
)
type getFileDesc struct{}
func (g getFileDesc) Complete(ctx *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
req, err := g.readJsonBody(ctx)
if err != nil {
return g.formError(ctx, err, method, err.Error(), codes.InvalidArgument)
}
timeout := config.GetRemote().(*conf.RemoteConfig).GrpcSetting.GetStreamInvokeTimeout()
stream, cancel, err := openStream(&ctx.Request.Header, method, timeout, client)
defer func() {
if cancel != nil {
cancel()
}
}()
if err != nil {
return g.formError(ctx, err, method, errorMsgInternal, codes.Internal)
}
if req != nil {
value := u.ConvertInterfaceToGrpcStruct(req)
err := stream.Send(backend.WrapBody(value))
if err != nil {
return g.formError(ctx, err, method, errorMsgInternal, codes.Internal)
}
}
msg, err := stream.Recv()
if err != nil {
response, status, err := getResponse(nil, err)
if err == nil {
ctx.SetStatusCode(status)
ctx.SetBody(response)
}
return domain.Create().SetError(err)
}
bf := s.BeginFile{}
err = bf.FromMessage(msg)
if err != nil {
response, status, err := getResponse(nil, err)
if err == nil {
ctx.SetStatusCode(status)
ctx.SetBody(response)
}
return domain.Create().SetError(err)
}
header := &ctx.Response.Header
header.Set(headerKeyContentDisposition, fmt.Sprintf("attachment; filename=%s", bf.FileName))
header.Set(headerKeyContentType, bf.ContentType)
if bf.ContentLength > 0 {
header.Set(headerKeyContentLength, strconv.Itoa(int(bf.ContentLength)))
} else {
header.Set(headerKeyTransferEncoding, "chunked")
}
err = g.write(ctx, stream, method)
return domain.Create().SetError(err)
}
func (getFileDesc) write(ctx *fasthttp.RequestCtx, stream isp.BackendService_RequestStreamClient, method string) error {
for {
msg, err := stream.Recv()
if s.IsEndOfFile(msg) || err == io.EOF {
return nil
}
if err != nil {
logHandlerError(log_code.TypeData.GetFile, method, err)
return err
}
bytes := msg.GetBytesBody()
if bytes == nil {
log.WithMetadata(map[string]interface{}{
log_code.MdTypeData: log_code.TypeData.GetFile,
log_code.MdMethod: method,
}).Errorf(log_code.WarnProxyGrpcHandler, "Method %s. Expected bytes array", method)
return nil
}
_, err = ctx.Write(bytes)
if err != nil {
logHandlerError(log_code.TypeData.GetFile, method, err)
return err
}
}
}
func (getFileDesc) readJsonBody(ctx *fasthttp.RequestCtx) (interface{}, error) {
requestBody := ctx.Request.Body()
var body interface{}
if len(requestBody) == 0 {
requestBody = []byte("{}")
}
switch requestBody[0] {
case '{':
body = make(map[string]interface{})
case '[':
body = make([]interface{}, 0)
default:
return nil, errInvalidJson
}
err := json.Unmarshal(requestBody, &body)
if err != nil {
return nil, err
}
return body, err
}
func (getFileDesc) formError(ctx *fasthttp.RequestCtx, err error, method, msg string, code codes.Code) domain.ProxyResponse {
logHandlerError(log_code.TypeData.GetFile, method, err)
utils.WriteError(ctx, msg, code, nil)
return domain.Create().SetError(err)
}
@@ -1,158 +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"
s "github.com/integration-system/isp-lib/v2/streaming"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"mime/multipart"
"strings"
)
var sendMultipartData sendMultipartDataDesc
type sendMultipartDataDesc struct{}
func (h sendMultipartDataDesc) Complete(c *fasthttp.RequestCtx, method string, client *backend.RxGrpcClient) domain.ProxyResponse {
cfg := config.GetRemote().(*conf.RemoteConfig).GrpcSetting
timeout := cfg.GetStreamInvokeTimeout()
stream, cancel, err := openStream(&c.Request.Header, method, timeout, client)
defer func() {
if cancel != nil {
cancel()
}
}()
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.WriteError(c, errorMsgInternal, codes.Internal, nil)
return domain.Create().SetError(err)
}
form, err := c.MultipartForm()
defer func() {
if form != nil {
_ = form.RemoveAll()
}
}()
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
utils.WriteError(c, errorMsgInvalidArg, codes.InvalidArgument, nil)
return domain.Create().SetError(err)
}
resp, proxyResp, ok := h.formResponse(c, stream, form, method)
err = stream.CloseSend()
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
}
if ok {
arrayBody := strings.Join(resp, ",")
_, err = c.WriteString("[" + arrayBody + "]")
if err != nil {
logHandlerError(log_code.TypeData.SendMultipart, method, err)
}
}
return proxyResp
}
func (h sendMultipartDataDesc) formResponse(c *fasthttp.RequestCtx, stream isp.BackendService_RequestStreamClient,
form *multipart.Form, method string) ([]string, domain.ProxyResponse, bool) {
formData := make(map[string]interface{}, len(form.Value))
for k, v := range form.Value {
if len(v) > 0 {
formData[k] = v[0]
}
}
var (
resp = make([]string, 0)
buffer = make([]byte, config.GetRemote().(*conf.RemoteConfig).GrpcSetting.GetTransferFileBufferSize())
proxyResp domain.ProxyResponse
ok = true
eof bool
err error
)
for formDataName, files := range form.File {
if len(files) == 0 {
continue
}
file := files[0]
fileName := file.Filename
contentType := file.Header.Get(headerKeyContentType)
contentLength := file.Size
bf := s.BeginFile{
FileName: fileName,
FormDataName: formDataName,
ContentType: contentType,
ContentLength: contentLength,
FormData: formData,
}
err = stream.Send(bf.ToMessage())
ok, eof, proxyResp = checkError(err, c, method)
if !ok || eof {
break
}
f, err := file.Open()
ok, eof, proxyResp = checkError(err, c, method)
if !ok || eof {
break
}
ok, eof, proxyResp = h.transferFile(f, stream, buffer, c, method)
if !ok || eof {
break
}
msg, invokeErr := stream.Recv()
ok, eof, proxyResp = checkError(invokeErr, c, method)
if !ok || eof {
break
}
response, _, err := getResponse(msg, invokeErr)
if err != nil {
ok = false
break
}
resp = append(resp, string(response))
}
return resp, proxyResp, ok
}
func (sendMultipartDataDesc) transferFile(f multipart.File, stream isp.BackendService_RequestStreamClient,
buffer []byte, ctx *fasthttp.RequestCtx, method string) (bool, bool, domain.ProxyResponse) {
var (
ok = true
eof bool
proxyResp domain.ProxyResponse
)
for {
n, err := f.Read(buffer)
if n > 0 {
err = stream.Send(&isp.Message{Body: &isp.Message_BytesBody{BytesBody: buffer[:n]}})
ok, eof, proxyResp = checkError(err, ctx, method)
if !ok || eof {
break
}
}
if err != nil {
ok, eof, proxyResp = checkError(err, ctx, method)
if ok && eof {
err = stream.Send(s.FileEnd())
ok, eof, proxyResp = checkError(err, ctx, method)
}
break
}
}
return ok, eof, proxyResp
}