go-micro.dev/v5@v5.12.0/config/source/nats/watcher.go (about)

     1  package nats
     2  
     3  import (
     4  	"time"
     5  
     6  	natsgo "github.com/nats-io/nats.go"
     7  	"go-micro.dev/v5/config/encoder"
     8  	"go-micro.dev/v5/config/source"
     9  )
    10  
    11  type watcher struct {
    12  	e      encoder.Encoder
    13  	name   string
    14  	bucket string
    15  	key    string
    16  
    17  	ch   chan *source.ChangeSet
    18  	exit chan bool
    19  }
    20  
    21  func newWatcher(kv natsgo.KeyValue, bucket, key, name string, e encoder.Encoder) (source.Watcher, error) {
    22  	w := &watcher{
    23  		e:      e,
    24  		name:   name,
    25  		bucket: bucket,
    26  		key:    key,
    27  		ch:     make(chan *source.ChangeSet),
    28  		exit:   make(chan bool),
    29  	}
    30  
    31  	wh, _ := kv.Watch(key)
    32  
    33  	go func() {
    34  		for {
    35  			select {
    36  			case v := <-wh.Updates():
    37  				if v != nil {
    38  					w.handle(v.Value())
    39  				}
    40  			case <-w.exit:
    41  				_ = wh.Stop()
    42  				return
    43  			}
    44  		}
    45  	}()
    46  	return w, nil
    47  }
    48  
    49  func (w *watcher) handle(data []byte) {
    50  	cs := &source.ChangeSet{
    51  		Timestamp: time.Now(),
    52  		Format:    w.e.String(),
    53  		Source:    w.name,
    54  		Data:      data,
    55  	}
    56  	cs.Checksum = cs.Sum()
    57  
    58  	w.ch <- cs
    59  }
    60  
    61  func (w *watcher) Next() (*source.ChangeSet, error) {
    62  	select {
    63  	case cs := <-w.ch:
    64  		return cs, nil
    65  	case <-w.exit:
    66  		return nil, source.ErrWatcherStopped
    67  	}
    68  }
    69  
    70  func (w *watcher) Stop() error {
    71  	select {
    72  	case <-w.exit:
    73  		return nil
    74  	default:
    75  		close(w.exit)
    76  	}
    77  
    78  	return nil
    79  }