2015-04-28 22:30:51 +00:00
|
|
|
package builtin
|
2015-04-08 05:46:05 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
2015-04-28 22:30:51 +00:00
|
|
|
|
2015-05-17 18:10:43 +00:00
|
|
|
"github.com/drone/drone/pkg/bus"
|
2015-04-08 05:46:05 +00:00
|
|
|
)
|
|
|
|
|
2015-05-17 18:10:43 +00:00
|
|
|
type Bus struct {
|
2015-04-08 05:46:05 +00:00
|
|
|
sync.Mutex
|
2015-05-17 18:10:43 +00:00
|
|
|
subs map[chan *bus.Event]bool
|
2015-04-08 05:46:05 +00:00
|
|
|
}
|
|
|
|
|
2015-05-17 18:10:43 +00:00
|
|
|
// New creates a new Bus that manages a list of
|
2015-04-08 05:46:05 +00:00
|
|
|
// subscribers to which events are published.
|
2015-05-17 18:10:43 +00:00
|
|
|
func New() *Bus {
|
|
|
|
return &Bus{
|
|
|
|
subs: make(map[chan *bus.Event]bool),
|
2015-04-08 05:46:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Subscribe adds the channel to the list of
|
|
|
|
// subscribers. Each subscriber in the list will
|
|
|
|
// receive broadcast events.
|
2015-05-17 18:10:43 +00:00
|
|
|
func (b *Bus) Subscribe(c chan *bus.Event) {
|
2015-04-08 05:46:05 +00:00
|
|
|
b.Lock()
|
|
|
|
b.subs[c] = true
|
|
|
|
b.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unsubscribe removes the channel from the
|
|
|
|
// list of subscribers.
|
2015-05-17 18:10:43 +00:00
|
|
|
func (b *Bus) Unsubscribe(c chan *bus.Event) {
|
2015-04-08 05:46:05 +00:00
|
|
|
b.Lock()
|
|
|
|
delete(b.subs, c)
|
|
|
|
b.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send dispatches a message to all subscribers.
|
2015-05-17 18:10:43 +00:00
|
|
|
func (b *Bus) Send(event *bus.Event) {
|
2015-04-08 05:46:05 +00:00
|
|
|
b.Lock()
|
|
|
|
defer b.Unlock()
|
|
|
|
|
2015-04-28 22:30:51 +00:00
|
|
|
for s := range b.subs {
|
2015-05-17 18:10:43 +00:00
|
|
|
go func(c chan *bus.Event) {
|
2015-04-08 05:46:05 +00:00
|
|
|
defer recover()
|
|
|
|
c <- event
|
|
|
|
}(s)
|
|
|
|
}
|
|
|
|
}
|