11 Star 11 Fork 0

Gitee 极速下载 / goa

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
此仓库是为了提升国内下载速度的镜像仓库,每日同步一次。 原始仓库: https://github.com/goadesign/goa
克隆/下载
canceler.go 2.32 KB
一键复制 编辑 原始数据 按行查看 历史
Nitin 提交于 2019-03-07 14:26 . Godoc updates for transport pkgs (#2028)
package middleware
import (
"context"
"sync"
"sync/atomic"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// StreamCanceler provides a middleware that can be used to gracefully stop
// streaming requests. To stop streaming requests, simply pass in a context
// with cancellation and cancel the context. When the context given to the
// StreamCanceler is canceled, it does the following:
// 1. Stops accepting further streaming requests and returns the code
// Unavailable with message "server is stopping".
// 2. Cancels the context of all streaming requests. Your request handler
// should obey to the cancelation of request context.
//
// Example:
//
// var (
// ctxCancel context.Context
// cancelFunc context.CancelFunc
// )
// ctxCancel, cancelFunc = context.WithCancel(parentCtx)
// streamInterceptor := StreamCanceler(ctxCancel)
// // Use the interceptor in your server and when you need to shutdown
// // your server, simply cancel the context given to the StreamCanceler interceptor.
// cancelFunc()
//
// // In your application code, look for context cancellation and respond with proper code.
// for {
// select {
// case <-ctx.Done():
// return status.Error(codes.Canceled, "canceled")
// ...
//
func StreamCanceler(ctx context.Context) grpc.StreamServerInterceptor {
var (
cancels = map[*context.CancelFunc]struct{}{}
cancelMu = new(sync.Mutex)
canceling uint32
)
go func() {
<-ctx.Done()
atomic.StoreUint32(&canceling, 1)
cancelMu.Lock()
defer cancelMu.Unlock()
for cancel := range cancels {
(*cancel)()
}
}()
return grpc.StreamServerInterceptor(func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if atomic.LoadUint32(&canceling) == 1 {
return status.Error(codes.Unavailable, "server is stopping")
}
var (
cctx = ss.Context()
cancel context.CancelFunc
)
cctx, cancel = context.WithCancel(cctx)
// add the cancel function
cancelMu.Lock()
cancels[&cancel] = struct{}{}
cancelMu.Unlock()
// invoke rpc
err := handler(srv, NewWrappedServerStream(cctx, ss))
// remove the cancel function
cancelMu.Lock()
delete(cancels, &cancel)
cancelMu.Unlock()
// cleanup the WithCancel
cancel()
return err
})
}
1
https://gitee.com/mirrors/goa.git
git@gitee.com:mirrors/goa.git
mirrors
goa
goa
v2.2.5

搜索帮助