Skip to content

Commit 4125205

Browse files
support remote task cancellation
1 parent c8ec1cb commit 4125205

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

cancel.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package relay
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"sync"
7+
)
8+
9+
func (srv *Server) runCancelListener(ctx context.Context) {
10+
defer srv.wg.Done()
11+
ch, closeFn := srv.rdb.SubscribeCancel(ctx)
12+
defer closeFn()
13+
for {
14+
select {
15+
case <-ctx.Done():
16+
return
17+
case id, ok := <-ch:
18+
if !ok {
19+
return
20+
}
21+
if srv.cancels.cancel(id) {
22+
srv.logger.Info(fmt.Sprintf("relay: cancelled running task %s", id))
23+
}
24+
}
25+
}
26+
}
27+
28+
type cancelRegistry struct {
29+
mu sync.Mutex
30+
m map[string]context.CancelFunc
31+
}
32+
33+
func newCancelRegistry() *cancelRegistry {
34+
return &cancelRegistry{m: make(map[string]context.CancelFunc)}
35+
}
36+
37+
func (c *cancelRegistry) add(id string, fn context.CancelFunc) {
38+
c.mu.Lock()
39+
c.m[id] = fn
40+
c.mu.Unlock()
41+
}
42+
43+
func (c *cancelRegistry) remove(id string) {
44+
c.mu.Lock()
45+
delete(c.m, id)
46+
c.mu.Unlock()
47+
}
48+
49+
func (c *cancelRegistry) cancel(id string) bool {
50+
c.mu.Lock()
51+
fn, ok := c.m[id]
52+
c.mu.Unlock()
53+
if ok {
54+
fn()
55+
}
56+
return ok
57+
}

0 commit comments

Comments
 (0)