2019-05-31 01:11:13 +03:00
|
|
|
// Package memory is a memory source
|
|
|
|
package memory
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2019-06-07 15:53:42 +03:00
|
|
|
"github.com/google/uuid"
|
2020-08-19 17:47:17 +03:00
|
|
|
"github.com/unistack-org/micro/v3/config/source"
|
2019-05-31 01:11:13 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type memory struct {
|
|
|
|
sync.RWMutex
|
|
|
|
ChangeSet *source.ChangeSet
|
|
|
|
Watchers map[string]*watcher
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *memory) Read() (*source.ChangeSet, error) {
|
|
|
|
s.RLock()
|
|
|
|
cs := &source.ChangeSet{
|
2019-08-11 13:05:35 +03:00
|
|
|
Format: s.ChangeSet.Format,
|
2019-05-31 01:11:13 +03:00
|
|
|
Timestamp: s.ChangeSet.Timestamp,
|
|
|
|
Data: s.ChangeSet.Data,
|
|
|
|
Checksum: s.ChangeSet.Checksum,
|
|
|
|
Source: s.ChangeSet.Source,
|
|
|
|
}
|
|
|
|
s.RUnlock()
|
|
|
|
return cs, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *memory) Watch() (source.Watcher, error) {
|
|
|
|
w := &watcher{
|
2019-06-07 15:53:42 +03:00
|
|
|
Id: uuid.New().String(),
|
2019-05-31 01:11:13 +03:00
|
|
|
Updates: make(chan *source.ChangeSet, 100),
|
|
|
|
Source: s,
|
|
|
|
}
|
|
|
|
|
|
|
|
s.Lock()
|
|
|
|
s.Watchers[w.Id] = w
|
|
|
|
s.Unlock()
|
|
|
|
return w, nil
|
|
|
|
}
|
|
|
|
|
2019-12-23 11:42:57 +03:00
|
|
|
func (m *memory) Write(cs *source.ChangeSet) error {
|
2020-06-16 19:10:52 +03:00
|
|
|
m.Update(cs)
|
2019-12-23 11:42:57 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-05-31 01:11:13 +03:00
|
|
|
// Update allows manual updates of the config data.
|
|
|
|
func (s *memory) Update(c *source.ChangeSet) {
|
|
|
|
// don't process nil
|
|
|
|
if c == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// hash the file
|
|
|
|
s.Lock()
|
|
|
|
// update changeset
|
|
|
|
s.ChangeSet = &source.ChangeSet{
|
|
|
|
Data: c.Data,
|
|
|
|
Format: c.Format,
|
|
|
|
Source: "memory",
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
}
|
|
|
|
s.ChangeSet.Checksum = s.ChangeSet.Sum()
|
|
|
|
|
|
|
|
// update watchers
|
|
|
|
for _, w := range s.Watchers {
|
|
|
|
select {
|
|
|
|
case w.Updates <- s.ChangeSet:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
s.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *memory) String() string {
|
|
|
|
return "memory"
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSource(opts ...source.Option) source.Source {
|
|
|
|
var options source.Options
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
|
|
|
|
|
|
|
s := &memory{
|
|
|
|
Watchers: make(map[string]*watcher),
|
|
|
|
}
|
|
|
|
|
|
|
|
if options.Context != nil {
|
|
|
|
c, ok := options.Context.Value(changeSetKey{}).(*source.ChangeSet)
|
|
|
|
if ok {
|
|
|
|
s.Update(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return s
|
|
|
|
}
|