summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJakob Borg <jakob@nym.se>2015-09-29 17:17:09 +0200
committerJakob Borg <jakob@nym.se>2015-10-02 07:59:24 +0200
commitd746b043c8f0b92218c430e97cdcb14d06df6f25 (patch)
treece8719ff158c01ce448441f4ccaa77e7809ef16f
parentbeb643c666f556d12f1bc1d7bdf2fc0e6727ddc4 (diff)
Subscribing to events should not bump event ID (fixes #2329)
-rw-r--r--lib/events/events.go20
-rw-r--r--lib/events/events_test.go5
2 files changed, 15 insertions, 10 deletions
diff --git a/lib/events/events.go b/lib/events/events.go
index 9f7c535229..cfb6bb5439 100644
--- a/lib/events/events.go
+++ b/lib/events/events.go
@@ -90,7 +90,7 @@ func (t EventType) MarshalText() ([]byte, error) {
const BufferSize = 64
type Logger struct {
- subs map[int]*Subscription
+ subs []*Subscription
nextID int
mutex sync.Mutex
}
@@ -104,7 +104,6 @@ type Event struct {
type Subscription struct {
mask EventType
- id int
events chan Event
timeout *time.Timer
}
@@ -118,7 +117,6 @@ var (
func NewLogger() *Logger {
return &Logger{
- subs: make(map[int]*Subscription),
mutex: sync.NewMutex(),
}
}
@@ -128,13 +126,13 @@ func (l *Logger) Log(t EventType, data interface{}) {
if debug {
dl.Debugln("log", l.nextID, t.String(), data)
}
+ l.nextID++
e := Event{
ID: l.nextID,
Time: time.Now(),
Type: t,
Data: data,
}
- l.nextID++
for _, s := range l.subs {
if s.mask&t != 0 {
select {
@@ -154,12 +152,10 @@ func (l *Logger) Subscribe(mask EventType) *Subscription {
}
s := &Subscription{
mask: mask,
- id: l.nextID,
events: make(chan Event, BufferSize),
timeout: time.NewTimer(0),
}
- l.nextID++
- l.subs[s.id] = s
+ l.subs = append(l.subs, s)
l.mutex.Unlock()
return s
}
@@ -169,7 +165,15 @@ func (l *Logger) Unsubscribe(s *Subscription) {
if debug {
dl.Debugln("unsubscribe")
}
- delete(l.subs, s.id)
+ for i, ss := range l.subs {
+ if s == ss {
+ last := len(l.subs) - 1
+ l.subs[i] = l.subs[last]
+ l.subs[last] = nil
+ l.subs = l.subs[:last]
+ break
+ }
+ }
close(s.events)
l.mutex.Unlock()
}
diff --git a/lib/events/events_test.go b/lib/events/events_test.go
index 2f91dafea8..8b194b746a 100644
--- a/lib/events/events_test.go
+++ b/lib/events/events_test.go
@@ -134,6 +134,7 @@ func TestIDs(t *testing.T) {
s := l.Subscribe(events.AllEvents)
defer l.Unsubscribe(s)
l.Log(events.DeviceConnected, "foo")
+ _ = l.Subscribe(events.AllEvents)
l.Log(events.DeviceConnected, "bar")
ev, err := s.Poll(timeout)
@@ -152,8 +153,8 @@ func TestIDs(t *testing.T) {
if ev.Data.(string) != "bar" {
t.Fatal("Incorrect event:", ev)
}
- if !(ev.ID > id) {
- t.Fatalf("ID not incremented (%d !> %d)", ev.ID, id)
+ if ev.ID != id+1 {
+ t.Fatalf("ID not incremented (%d != %d)", ev.ID, id+1)
}
}