memory.go 1.7 KB

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