Skip to content

Commit 04ed053

Browse files
committed
Leverage built-in sync map for readability
1 parent b3b67ea commit 04ed053

File tree

1 file changed

+8
-25
lines changed

1 file changed

+8
-25
lines changed

grpc/middleware/canceler.go

+8-25
Original file line numberDiff line numberDiff line change
@@ -39,44 +39,27 @@ import (
3939
// ...
4040
func StreamCanceler(ctx context.Context) grpc.StreamServerInterceptor {
4141
var (
42-
cancels = map[*context.CancelFunc]struct{}{}
43-
cancelMu = new(sync.Mutex)
42+
cancels sync.Map
4443
canceling uint32
4544
)
4645

4746
go func() {
4847
<-ctx.Done()
4948
atomic.StoreUint32(&canceling, 1)
50-
cancelMu.Lock()
51-
defer cancelMu.Unlock()
52-
for cancel := range cancels {
49+
cancels.Range(func(key any, value any) bool {
50+
cancel := key.(*context.CancelFunc)
5351
(*cancel)()
54-
}
52+
return true
53+
})
5554
}()
5655
return grpc.StreamServerInterceptor(func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
5756
if atomic.LoadUint32(&canceling) == 1 {
5857
return status.Error(codes.Unavailable, "server is stopping")
5958
}
60-
var (
61-
cctx = ss.Context()
62-
cancel context.CancelFunc
63-
)
64-
cctx, cancel = context.WithCancel(cctx)
65-
66-
// add the cancel function
67-
cancelMu.Lock()
68-
cancels[&cancel] = struct{}{}
69-
cancelMu.Unlock()
70-
71-
// invoke rpc
59+
cctx, cancel := context.WithCancel(ss.Context())
60+
cancels.Store(&cancel, struct{}{})
7261
err := handler(srv, NewWrappedServerStream(cctx, ss))
73-
74-
// remove the cancel function
75-
cancelMu.Lock()
76-
delete(cancels, &cancel)
77-
cancelMu.Unlock()
78-
79-
// cleanup the WithCancel
62+
cancels.Delete(&cancel)
8063
cancel()
8164

8265
return err

0 commit comments

Comments
 (0)