github.com/annwntech/go-micro/v2@v2.9.5/config/source/memory/memory.go (about)

     1  // Package memory is a memory source
     2  package memory
     3  
     4  import (
     5  	"sync"
     6  	"time"
     7  
     8  	"github.com/google/uuid"
     9  	"github.com/annwntech/go-micro/v2/config/source"
    10  )
    11  
    12  type memory struct {
    13  	sync.RWMutex
    14  	ChangeSet *source.ChangeSet
    15  	Watchers  map[string]*watcher
    16  }
    17  
    18  func (s *memory) Read() (*source.ChangeSet, error) {
    19  	s.RLock()
    20  	cs := &source.ChangeSet{
    21  		Format:    s.ChangeSet.Format,
    22  		Timestamp: s.ChangeSet.Timestamp,
    23  		Data:      s.ChangeSet.Data,
    24  		Checksum:  s.ChangeSet.Checksum,
    25  		Source:    s.ChangeSet.Source,
    26  	}
    27  	s.RUnlock()
    28  	return cs, nil
    29  }
    30  
    31  func (s *memory) Watch() (source.Watcher, error) {
    32  	w := &watcher{
    33  		Id:      uuid.New().String(),
    34  		Updates: make(chan *source.ChangeSet, 100),
    35  		Source:  s,
    36  	}
    37  
    38  	s.Lock()
    39  	s.Watchers[w.Id] = w
    40  	s.Unlock()
    41  	return w, nil
    42  }
    43  
    44  func (m *memory) Write(cs *source.ChangeSet) error {
    45  	m.Update(cs)
    46  	return nil
    47  }
    48  
    49  // Update allows manual updates of the config data.
    50  func (s *memory) Update(c *source.ChangeSet) {
    51  	// don't process nil
    52  	if c == nil {
    53  		return
    54  	}
    55  
    56  	// hash the file
    57  	s.Lock()
    58  	// update changeset
    59  	s.ChangeSet = &source.ChangeSet{
    60  		Data:      c.Data,
    61  		Format:    c.Format,
    62  		Source:    "memory",
    63  		Timestamp: time.Now(),
    64  	}
    65  	s.ChangeSet.Checksum = s.ChangeSet.Sum()
    66  
    67  	// update watchers
    68  	for _, w := range s.Watchers {
    69  		select {
    70  		case w.Updates <- s.ChangeSet:
    71  		default:
    72  		}
    73  	}
    74  	s.Unlock()
    75  }
    76  
    77  func (s *memory) String() string {
    78  	return "memory"
    79  }
    80  
    81  func NewSource(opts ...source.Option) source.Source {
    82  	var options source.Options
    83  	for _, o := range opts {
    84  		o(&options)
    85  	}
    86  
    87  	s := &memory{
    88  		Watchers: make(map[string]*watcher),
    89  	}
    90  
    91  	if options.Context != nil {
    92  		c, ok := options.Context.Value(changeSetKey{}).(*source.ChangeSet)
    93  		if ok {
    94  			s.Update(c)
    95  		}
    96  	}
    97  
    98  	return s
    99  }