forked from pocketbase/pocketbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
broker.go
70 lines (56 loc) · 1.45 KB
/
broker.go
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
package subscriptions
import (
"fmt"
"sync"
)
// Broker defines a struct for managing subscriptions clients.
type Broker struct {
clients map[string]Client
mux sync.RWMutex
}
// NewBroker initializes and returns a new Broker instance.
func NewBroker() *Broker {
return &Broker{
clients: make(map[string]Client),
}
}
// Clients returns a shallow copy of all registered clients indexed
// with their connection id.
func (b *Broker) Clients() map[string]Client {
b.mux.RLock()
defer b.mux.RUnlock()
copy := make(map[string]Client, len(b.clients))
for id, c := range b.clients {
copy[id] = c
}
return copy
}
// ClientById finds a registered client by its id.
//
// Returns non-nil error when client with clientId is not registered.
func (b *Broker) ClientById(clientId string) (Client, error) {
b.mux.RLock()
defer b.mux.RUnlock()
client, ok := b.clients[clientId]
if !ok {
return nil, fmt.Errorf("No client associated with connection ID %q", clientId)
}
return client, nil
}
// Register adds a new client to the broker instance.
func (b *Broker) Register(client Client) {
b.mux.Lock()
defer b.mux.Unlock()
b.clients[client.Id()] = client
}
// Unregister removes a single client by its id.
//
// If client with clientId doesn't exist, this method does nothing.
func (b *Broker) Unregister(clientId string) {
b.mux.Lock()
defer b.mux.Unlock()
if client, ok := b.clients[clientId]; ok {
client.Discard()
delete(b.clients, clientId)
}
}