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