events_test.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. package events
  2. import (
  3. "net/http/httptest"
  4. "path/filepath"
  5. "sync"
  6. "testing"
  7. "time"
  8. "imuslab.com/arozos/mod/cluster/membership"
  9. )
  10. func init() {
  11. membership.HeartbeatInterval = 500 * time.Millisecond
  12. membership.OnlineWindow = 2 * time.Second
  13. membership.OfflineWindow = 4 * time.Second
  14. }
  15. type testNode struct {
  16. m *membership.Manager
  17. bus *Bus
  18. srv *httptest.Server
  19. }
  20. func newTestNode(t *testing.T, id string, runner HookRunner) *testNode {
  21. t.Helper()
  22. dir := t.TempDir()
  23. m, err := membership.NewManager(membership.Option{NodeID: id, DBFile: filepath.Join(dir, "c.db"), KeyFile: filepath.Join(dir, "k"), Version: "t", DefaultName: id})
  24. if err != nil {
  25. t.Fatalf("NewManager: %v", err)
  26. }
  27. bus, err := New(m, runner)
  28. if err != nil {
  29. t.Fatalf("events.New: %v", err)
  30. }
  31. srv := httptest.NewServer(m.ACNHandler())
  32. cfg := m.Config()
  33. cfg.AdvertiseURL = srv.URL
  34. m.UpdateConfig(cfg)
  35. t.Cleanup(func() { bus.Close(); m.Close(); srv.Close() })
  36. return &testNode{m: m, bus: bus, srv: srv}
  37. }
  38. func waitFor(t *testing.T, what string, d time.Duration, cond func() bool) {
  39. t.Helper()
  40. deadline := time.Now().Add(d)
  41. for !cond() {
  42. if time.Now().After(deadline) {
  43. t.Fatalf("timed out waiting for %s", what)
  44. }
  45. time.Sleep(25 * time.Millisecond)
  46. }
  47. }
  48. func TestMatches(t *testing.T) {
  49. tests := []struct {
  50. types []string
  51. ev string
  52. want bool
  53. }{
  54. {[]string{"*"}, "file.created", true},
  55. {[]string{"file.created"}, "file.created", true},
  56. {[]string{"file.created"}, "file.removed", false},
  57. {[]string{"file.*"}, "file.removed", true},
  58. {[]string{"node.*"}, "file.removed", false},
  59. {[]string{"FILE.Created"}, "file.created", true},
  60. }
  61. for _, tc := range tests {
  62. if got := matches(typeSet(tc.types), tc.ev); got != tc.want {
  63. t.Errorf("matches(%v, %s) = %v", tc.types, tc.ev, got)
  64. }
  65. }
  66. }
  67. func TestLocalPublishSubscribeDedup(t *testing.T) {
  68. n := newTestNode(t, "solo", nil)
  69. var mu sync.Mutex
  70. got := []Event{}
  71. unsub := n.bus.Subscribe([]string{"file.*"}, func(e Event) { mu.Lock(); got = append(got, e); mu.Unlock() })
  72. n.bus.Publish(Event{Type: "file.created", Path: "/a"})
  73. n.bus.Publish(Event{Type: "node.online"})
  74. n.bus.Publish(Event{ID: "dup", Type: "file.removed"})
  75. n.bus.Publish(Event{ID: "dup", Type: "file.removed"})
  76. mu.Lock()
  77. if len(got) != 2 || got[0].Path != "/a" || got[0].Node != "solo" || got[0].ID == "" {
  78. t.Errorf("got %+v", got)
  79. }
  80. mu.Unlock()
  81. unsub()
  82. n.bus.Publish(Event{Type: "file.created"})
  83. mu.Lock()
  84. if len(got) != 2 {
  85. t.Errorf("unsubscribed listener still called")
  86. }
  87. mu.Unlock()
  88. }
  89. func TestFanOutAndHooks(t *testing.T) {
  90. var runMu sync.Mutex
  91. runs := []string{}
  92. runner := func(h Hook, ev Event) error {
  93. runMu.Lock()
  94. runs = append(runs, h.Script+":"+ev.Type)
  95. runMu.Unlock()
  96. return nil
  97. }
  98. a := newTestNode(t, "node-a", runner)
  99. b := newTestNode(t, "node-b", runner)
  100. a.m.CreateCluster("Ev")
  101. token, _, _ := a.m.NewJoinToken(time.Hour)
  102. if _, err := b.m.JoinCluster(token); err != nil {
  103. t.Fatalf("join: %v", err)
  104. }
  105. waitFor(t, "b online at a", 5*time.Second, func() bool {
  106. for _, n := range a.m.NodeViews() {
  107. if n.ID == "node-b" && n.State == membership.StateOnline {
  108. return true
  109. }
  110. }
  111. return false
  112. })
  113. var mu sync.Mutex
  114. seenOnB := []Event{}
  115. b.bus.Subscribe([]string{"file.created"}, func(e Event) { mu.Lock(); seenOnB = append(seenOnB, e); mu.Unlock() })
  116. if _, err := b.bus.AddHook("toby", []string{"file.*"}, "user:/hook.agi"); err != nil {
  117. t.Fatalf("AddHook: %v", err)
  118. }
  119. a.bus.Publish(Event{Type: "file.created", Path: "/x", User: "toby"})
  120. waitFor(t, "event to reach b", 5*time.Second, func() bool {
  121. mu.Lock()
  122. defer mu.Unlock()
  123. return len(seenOnB) == 1 && seenOnB[0].Node == "node-a" && seenOnB[0].Path == "/x"
  124. })
  125. waitFor(t, "hook to run on b", 5*time.Second, func() bool {
  126. runMu.Lock()
  127. defer runMu.Unlock()
  128. return len(runs) == 1 && runs[0] == "user:/hook.agi:file.created"
  129. })
  130. hooks := b.bus.Hooks("toby")
  131. if len(hooks) != 1 || hooks[0].RunCount != 1 || hooks[0].LastRun == 0 {
  132. t.Errorf("hook bookkeeping: %+v", hooks)
  133. }
  134. if err := b.bus.RemoveHook(hooks[0].ID, "alice"); err == nil {
  135. t.Errorf("other user removed hook")
  136. }
  137. if err := b.bus.RemoveHook(hooks[0].ID, "toby"); err != nil {
  138. t.Errorf("RemoveHook: %v", err)
  139. }
  140. if len(b.bus.Hooks("")) != 0 {
  141. t.Errorf("hook still listed")
  142. }
  143. //Hooks persist across bus restarts
  144. b.bus.AddHook("toby", []string{"node.*"}, "user:/n.agi")
  145. nb := &Bus{m: b.m, hooks: map[string]*Hook{}}
  146. nb.loadHooks()
  147. if len(nb.Hooks("toby")) != 1 {
  148. t.Errorf("hook not persisted")
  149. }
  150. }