github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/registry/client/watcher.go (about) 1 package client 2 3 import ( 4 "time" 5 6 pb "github.com/tickoalcantara12/micro/v3/proto/registry" 7 "github.com/tickoalcantara12/micro/v3/service/registry" 8 "github.com/tickoalcantara12/micro/v3/service/registry/util" 9 ) 10 11 type serviceWatcher struct { 12 stream pb.Registry_WatchService 13 closed chan bool 14 } 15 16 func (s *serviceWatcher) Next() (*registry.Result, error) { 17 var i int 18 19 for { 20 // check if closed 21 select { 22 case <-s.closed: 23 return nil, registry.ErrWatcherStopped 24 default: 25 } 26 27 r, err := s.stream.Recv() 28 if err != nil { 29 return nil, err 30 } 31 32 // result is nil 33 if r == nil { 34 i++ 35 36 // only process for 3 attempts if nil 37 if i > 3 { 38 return nil, registry.ErrWatcherStopped 39 } 40 41 // wait a moment 42 time.Sleep(time.Second) 43 44 // otherwise continue 45 continue 46 } 47 48 return ®istry.Result{ 49 Action: r.Action, 50 Service: util.ToService(r.Service), 51 }, nil 52 } 53 } 54 55 func (s *serviceWatcher) Stop() { 56 select { 57 case <-s.closed: 58 return 59 default: 60 close(s.closed) 61 s.stream.Close() 62 } 63 } 64 65 func newWatcher(stream pb.Registry_WatchService) registry.Watcher { 66 return &serviceWatcher{ 67 stream: stream, 68 closed: make(chan bool), 69 } 70 }