Debian Codegraph @

api/v0/detector/zoo/client2.go

raw symbols SCIP
1 package zoo
2
3 import (
4 "sync"
5 "time"
6
7 "github.com/samuel/go-zookeeper/zk"
8 )
9
10 const (
11 defaultSessionTimeout = 60 * time.Second
12 CurrentPath = "."
13 )
14
15 var zkSessionTimeout = defaultSessionTimeout
16
17 type client2 struct {
18 *zk.Conn
19 path string
20 done chan struct{} // signal chan, closes when the underlying connection terminates
21 stopOnce sync.Once
22 }
23
24 func connect2(hosts []string, path string) (*client2, error) {
25 c, ev, err := zk.Connect(hosts, zkSessionTimeout)
26 if err != nil {
27 return nil, err
28 }
29 done := make(chan struct{})
30 go func() {
31 // close the 'done' chan when the zk event chan closes (signals termination of zk connection)
32 defer close(done)
33 for {
34 if _, ok := <-ev; !ok {
35 return
36 }
37 }
38 }()
39 return &client2{
40 Conn: c,
41 path: path,
42 done: done,
43 }, nil
44 }
45
46 func (c *client2) Stopped() <-chan struct{} {
47 return c.done
48 }
49
50 func (c *client2) Stop() {
51 c.stopOnce.Do(c.Close)
52 }
53
54 func (c *client2) Data(path string) (data []byte, err error) {
55 data, _, err = c.Get(path)
56 return
57 }
58
59 func (c *client2) WatchChildren(path string) (string, <-chan []string, <-chan error) {
60 errCh := make(chan error, 1)
61 snap := make(chan []string)
62
63 watchPath := c.path
64 if path != "" && path != CurrentPath {
65 watchPath = watchPath + path
66 }
67 go func() {
68 defer close(errCh)
69 for {
70 children, _, ev, err := c.ChildrenW(watchPath)
71 if err != nil {
72 errCh <- err
73 return
74 }
75 select {
76 case snap <- children:
77 case <-c.done:
78 return
79 }
80 e := <-ev // wait for the next watch-related event
81 if e.Err != nil {
82 errCh <- e.Err
83 return
84 }
85 }
86 }()
87 return watchPath, snap, errCh
88 }