聊聊dubbo-go-proxy的timeoutFilter

codecraft

本文主要研究一下dubbo-go-proxy的timeoutFilter

timeoutFilter

dubbo-go-proxy/pkg/filter/timeout/timeout.go

func Init() {
    extension.SetFilterFunc(constant.TimeoutFilter, timeoutFilterFunc(0))
}

func timeoutFilterFunc(duration time.Duration) fc.FilterFunc {
    return New(duration).Do()
}

// timeoutFilter is a filter for control request time out.
type timeoutFilter struct {
    // global timeout
    waitTime time.Duration
}

// New create timeout filter.
func New(t time.Duration) filter.Filter {
    if t <= 0 {
        t = constant.DefaultTimeout
    }
    return &timeoutFilter{
        waitTime: t,
    }
}
timeoutFilter往extension设置了名为`dgp.filters.timeout的timeoutFilterFunc,默认的timeout为1s;timeoutFilterFunc执行的是timeoutFilter的Do方法

Do

dubbo-go-proxy/pkg/filter/timeout/timeout.go

// Do execute timeoutFilter filter logic.
func (f timeoutFilter) Do() fc.FilterFunc {
    return func(c fc.Context) {
        hc := c.(*contexthttp.HttpContext)

        ctx, cancel := context.WithTimeout(hc.Ctx, f.getTimeout(hc.Timeout))
        defer cancel()
        // Channel capacity must be greater than 0.
        // Otherwise, if the parent coroutine quit due to timeout,
        // the child coroutine may never be able to quit.
        finishChan := make(chan struct{}, 1)
        go func() {
            // panic by recovery
            c.Next()
            finishChan <- struct{}{}
        }()

        select {
        // timeout do.
        case <-ctx.Done():
            logger.Warnf("api:%s request timeout", hc.GetAPI().URLPattern)
            bt, _ := json.Marshal(filter.ErrResponse{Message: http.ErrHandlerTimeout.Error()})
            hc.SourceResp = bt
            hc.TargetResp = &client.Response{Data: bt}
            hc.WriteJSONWithStatus(http.StatusGatewayTimeout, bt)
            c.Abort()
        case <-finishChan:
            // finish call do something.
        }
    }
}

func (f timeoutFilter) getTimeout(t time.Duration) time.Duration {
    if t <= 0 {
        return f.waitTime
    }

    return t
}
Do方法会通过context.WithTimeout创建ctx及cancel,然后注册defer这个cancel func;之后创建finishChan,异步执行c.Next(),之后往finishChan写入数据;最后select判断ctx.Done()或者是finishChan;如果是ctx.Done()则表示timeout了,返回http.StatusGatewayTimeout

小结

dubbo-go-proxy的timeoutFilter默认设置了1s超时,它通过context.WithTimeout创建ctx及cancel,并异步执行c.Next(),若ctx.Done()则表示timeout了,返回http.StatusGatewayTimeout;若是读取到了finishChan则表示请求正常响应。

doc

阅读 487

code-craft
spring boot , docker and so on 欢迎关注微信公众号: geek_luandun

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下了或重如泰山或轻如鸿毛的几笔。

11.4k 声望
1.1k 粉丝
0 条评论

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下了或重如泰山或轻如鸿毛的几笔。

11.4k 声望
1.1k 粉丝
宣传栏