-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathcanceler.go
85 lines (76 loc) Β· 2.32 KB
/
canceler.go
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
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
})
}