layer.go 3.4 KB
Newer Older
Y
Your Name 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
package application

import (
	"context"
	"time"

	"github.com/eolinker/goku-api-gateway/config"
	log "github.com/eolinker/goku-api-gateway/goku-log"
	"github.com/eolinker/goku-api-gateway/goku-node/common"
	"github.com/eolinker/goku-api-gateway/node/gateway/application/backend"
	"github.com/eolinker/goku-api-gateway/node/gateway/application/interpreter"
	"github.com/eolinker/goku-api-gateway/node/gateway/response"
)

type LayerApplication struct {
	output    response.Encoder
	backsides []*backend.Layer
	static    *staticeResponse

	timeOut time.Duration
}

func (app *LayerApplication) Execute(ctx *common.Context) {

	orgBody, _ := ctx.ProxyRequest.RawBody()

	bodyObj, _ := ctx.ProxyRequest.BodyInterface()

	variables := interpreter.NewVariables(orgBody, bodyObj, ctx.ProxyRequest.Headers(), ctx.ProxyRequest.Cookies(), ctx.RestfulParam, ctx.ProxyRequest.Querys(), len(app.backsides))

	deadline := context.Background()
	cancelFunc := context.CancelFunc(nil)
	app.timeOut = 0
	if app.timeOut > 0 {
		deadline, cancelFunc = context.WithDeadline(deadline, time.Now().Add(app.timeOut))
	} else {
		deadline, cancelFunc = context.WithCancel(deadline)
	}

	resC := make(chan int, 1)
	errC := make(chan error, 1)
	go app.do(deadline, variables, ctx, resC, errC)

	defer func() {
		close(resC)
		close(errC)
	}()

	select {
	case <-deadline.Done():
		ctx.SetStatus(503, "503")
		ctx.SetBody([]byte("[ERROR]timeout!"))
		// 超时
		return
	case <-errC:

		cancelFunc()
		ctx.SetStatus(504, "504")
		ctx.SetBody([]byte("[ERROR]Fail to get response after proxy!"))
		//error
		return
	case <-resC:
		//response
		cancelFunc()
		break
	}

	mergeResponse, headers := variables.MergeResponse()

	body, e := app.output.Encode(mergeResponse, nil)
	if e != nil {
		log.Warn("encode response error:", e)
		return
	}

	ctx.SetProxyResponseHandler(common.NewResponseReader(headers, 200, "200", body))

}
func (app *LayerApplication) do(ctxDeadline context.Context, variables *interpreter.Variables, ctx *common.Context, resC chan<- int, errC chan<- error) {

	l := len(app.backsides)
	for i, b := range app.backsides {

		if deadline, ok := ctxDeadline.Deadline(); ok {
			if time.Now().After(deadline) {
				// 超时
				log.Warn("time out before send step:", i, "/", l)
				return
			}
		}
		r, err := b.Send(ctx, variables, ctxDeadline)

		if deadline, ok := ctxDeadline.Deadline(); ok {
			if time.Now().After(deadline) {
				// 超时
				log.Warn("time out before send step:", i+1, "/", l)
				return
			}
		}
		if err != nil {
			errC <- err
			log.Warn("error by send step:", i+1, "/", l, "\t:", err)
			return
		}
		variables.AppendResponse(r.Header, r.Body)
	}
	if deadline, ok := ctxDeadline.Deadline(); ok {
		if time.Now().After(deadline) {
			// 超时
			log.Warn("time out before send step:", l, "/", l)
			return
		}
	}
	resC <- 1

}
func NewLayerApplication(apiContent *config.APIContent) *LayerApplication {
	app := &LayerApplication{
		output:    response.GetEncoder(apiContent.OutPutEncoder),
		backsides: make([]*backend.Layer, 0, len(apiContent.Steps)),
		static:    nil,
		timeOut:   time.Duration(apiContent.TimeOutTotal) * time.Millisecond,
	}

	for _, step := range apiContent.Steps {
		app.backsides = append(app.backsides, backend.NewLayer(step))
	}

	if apiContent.StaticResponse != "" {
		staticResponseStrategy := config.Parse(apiContent.StaticResponseStrategy)
		app.static = newStaticeResponse(apiContent.StaticResponse, staticResponseStrategy)
	}
	return app
}