aboutsummaryrefslogtreecommitdiff
path: root/bus.go
blob: 86e9cf7db95d56a7d1d20c210981f2b0f7cd65a1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Package eventbus представляет собой асинхронную шину событий
package eventbus

import (
	"context"
	"strings"
	"sync"
)

const (
	defaultCapacity = 32
)

type Bus struct {
	noCopy

	listeners     node[Listener]
	nameSeparator string
	wildcard      string
}

func New(opts ...Opt) *Bus {
	b := &Bus{
		nameSeparator: ".",
		wildcard:      "*",
	}

	for _, o := range opts {
		o.Apply(b)
	}

	if cap(b.listeners.values) == 0 {
		b.listeners = node[Listener]{
			children: make(map[string]*node[Listener], defaultCapacity),
			values:   make([]Listener, 0, defaultCapacity),
		}
	}

	return b
}

type Listener chan Event

type Event interface {
	Event() string
}

// Subscribe to an event at the specified path. Returns a listener channel for
// receiving events.
func (b *Bus) Subscribe(ctx context.Context, path string) Listener {
	splitedPath := strings.Split(path, b.nameSeparator)
	ch := make(Listener, 1)
	b.listeners.Put(splitedPath, ch)
	go func() {
		<-ctx.Done()
		close(ch)
		b.listeners.Remove(ch)
	}()
	return ch
}

// Publish an event to all subscribers who are subscribed to the corresponding
// event path.
func (b *Bus) Publish(ev Event) {
	splitedEventName := strings.Split(ev.Event(), b.nameSeparator)
	listeners := b.listeners.Get(splitedEventName, b.wildcard)

	wg := sync.WaitGroup{}
	for _, l := range listeners {
		wg.Go(func() {
			select {
			case l <- ev:
			default:
			}
		})
	}
	wg.Wait()
}

// Close the event bus and all listener channels.
func (b *Bus) Close() {
	b.listeners.Clear(func(value Listener) {
		close(value)
	})
}

type noCopy struct{}

func (*noCopy) Lock() {}

func (*noCopy) Unlock() {}