summaryrefslogtreecommitdiffstats
path: root/modules/eventsource/manager.go
blob: 730cacd9405163ec70c1ed6467824d47a5e77673 (plain)
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
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package eventsource

import (
	"sync"
)

// Manager manages the eventsource Messengers
type Manager struct {
	mutex sync.Mutex

	messengers map[int64]*Messenger
	connection chan struct{}
}

var manager *Manager

func init() {
	manager = &Manager{
		messengers: make(map[int64]*Messenger),
		connection: make(chan struct{}, 1),
	}
}

// GetManager returns a Manager and initializes one as singleton if there's none yet
func GetManager() *Manager {
	return manager
}

// Register message channel
func (m *Manager) Register(uid int64) <-chan *Event {
	m.mutex.Lock()
	messenger, ok := m.messengers[uid]
	if !ok {
		messenger = NewMessenger(uid)
		m.messengers[uid] = messenger
	}
	select {
	case m.connection <- struct{}{}:
	default:
	}
	m.mutex.Unlock()
	return messenger.Register()
}

// Unregister message channel
func (m *Manager) Unregister(uid int64, channel <-chan *Event) {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	messenger, ok := m.messengers[uid]
	if !ok {
		return
	}
	if messenger.Unregister(channel) {
		delete(m.messengers, uid)
	}
}

// UnregisterAll message channels
func (m *Manager) UnregisterAll() {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	for _, messenger := range m.messengers {
		messenger.UnregisterAll()
	}
	m.messengers = map[int64]*Messenger{}
}

// SendMessage sends a message to a particular user
func (m *Manager) SendMessage(uid int64, message *Event) {
	m.mutex.Lock()
	messenger, ok := m.messengers[uid]
	m.mutex.Unlock()
	if ok {
		messenger.SendMessage(message)
	}
}