2019-04-21 00:38:12 +00:00
|
|
|
package server
|
|
|
|
|
2019-12-01 01:08:11 +00:00
|
|
|
import (
|
2020-01-18 22:04:26 +00:00
|
|
|
"sync"
|
2019-12-01 01:08:11 +00:00
|
|
|
)
|
|
|
|
|
2019-04-21 00:38:12 +00:00
|
|
|
// Defines all of the possible output events for a server.
|
2019-05-28 01:03:37 +00:00
|
|
|
// noinspection GoNameStartsWithPackageName
|
2019-04-21 00:38:12 +00:00
|
|
|
const (
|
2020-01-18 21:05:44 +00:00
|
|
|
DaemonMessageEvent = "daemon message"
|
|
|
|
InstallOutputEvent = "install output"
|
2019-05-28 00:12:51 +00:00
|
|
|
ConsoleOutputEvent = "console output"
|
2019-12-01 01:08:11 +00:00
|
|
|
StatusEvent = "status"
|
|
|
|
StatsEvent = "stats"
|
2019-04-21 00:38:12 +00:00
|
|
|
)
|
|
|
|
|
2020-01-18 22:04:26 +00:00
|
|
|
type Event struct {
|
|
|
|
Data string
|
|
|
|
Topic string
|
|
|
|
}
|
2019-04-21 00:38:12 +00:00
|
|
|
|
2020-01-18 22:04:26 +00:00
|
|
|
type EventBus struct {
|
|
|
|
subscribers map[string][]chan Event
|
|
|
|
mu sync.Mutex
|
2019-04-21 00:38:12 +00:00
|
|
|
}
|
|
|
|
|
2020-01-18 22:04:26 +00:00
|
|
|
// Returns the server's emitter instance.
|
|
|
|
func (s *Server) Events() *EventBus {
|
|
|
|
if s.emitter == nil {
|
|
|
|
s.emitter = &EventBus{
|
|
|
|
subscribers: map[string][]chan Event{},
|
2019-04-21 00:38:12 +00:00
|
|
|
}
|
|
|
|
}
|
2020-01-18 22:04:26 +00:00
|
|
|
|
|
|
|
return s.emitter
|
2019-04-21 00:38:12 +00:00
|
|
|
}
|
|
|
|
|
2020-01-18 22:04:26 +00:00
|
|
|
// Publish data to a given topic.
|
|
|
|
func (e *EventBus) Publish(topic string, data string) {
|
|
|
|
e.mu.Lock()
|
|
|
|
defer e.mu.Unlock()
|
|
|
|
|
|
|
|
if ch, ok := e.subscribers[topic]; ok {
|
|
|
|
go func(data Event, cs []chan Event) {
|
|
|
|
for _, channel := range cs {
|
|
|
|
channel <- data
|
|
|
|
}
|
|
|
|
}(Event{Data: data, Topic: topic}, ch)
|
2019-04-21 00:38:12 +00:00
|
|
|
}
|
2019-12-01 01:08:11 +00:00
|
|
|
}
|
|
|
|
|
2020-01-18 22:04:26 +00:00
|
|
|
// Subscribe to an emitter topic using a channel.
|
|
|
|
func (e *EventBus) Subscribe(topic string, ch chan Event) {
|
|
|
|
e.mu.Lock()
|
|
|
|
defer e.mu.Unlock()
|
|
|
|
|
|
|
|
if p, ok := e.subscribers[topic]; ok {
|
|
|
|
e.subscribers[topic] = append(p, ch)
|
|
|
|
} else {
|
|
|
|
e.subscribers[topic] = append([]chan Event{}, ch)
|
|
|
|
}
|
2019-12-01 01:08:11 +00:00
|
|
|
}
|
2020-01-18 22:04:26 +00:00
|
|
|
|
|
|
|
// Unsubscribe a channel from a topic.
|
|
|
|
func (e *EventBus) Unsubscribe(topic string, ch chan Event) {
|
|
|
|
e.mu.Lock()
|
|
|
|
defer e.mu.Unlock()
|
|
|
|
|
|
|
|
if _, ok := e.subscribers[topic]; ok {
|
|
|
|
for i := range e.subscribers[topic] {
|
|
|
|
if ch == e.subscribers[topic][i] {
|
|
|
|
e.subscribers[topic] = append(e.subscribers[topic][:i], e.subscribers[topic][i+1:]...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|