pool.mx raw
1 package relay
2
3 // Pool manages connections to multiple relays.
4 type Pool struct {
5 conns map[string]*Conn
6 }
7
8 // NewPool creates a relay pool.
9 func NewPool() *Pool {
10 return &Pool{
11 conns: map[string]*Conn{},
12 }
13 }
14
15 // Connect gets or creates a connection to a relay.
16 func (p *Pool) Connect(url string) *Conn {
17 if c, ok := p.conns[url]; ok && c.state != StateClosed {
18 return c
19 }
20 p.evictClosed()
21 c := Dial(url)
22 p.conns[url] = c
23 return c
24 }
25
26 // Get returns an existing connection, or nil.
27 func (p *Pool) Get(url string) *Conn {
28 c, ok := p.conns[url]
29 if !ok || !c.IsOpen() {
30 return nil
31 }
32 return c
33 }
34
35 // Disconnect closes and removes a connection.
36 func (p *Pool) Disconnect(url string) {
37 if c, ok := p.conns[url]; ok {
38 c.Close()
39 delete(p.conns, url)
40 }
41 }
42
43 // CloseAll closes all connections.
44 func (p *Pool) CloseAll() {
45 for url, c := range p.conns {
46 c.Close()
47 delete(p.conns, url)
48 }
49 }
50
51 // URLs returns all connected relay URLs.
52 func (p *Pool) URLs() []string {
53 var out []string
54 for url, c := range p.conns {
55 if c.IsOpen() {
56 out = append(out, url)
57 }
58 }
59 return out
60 }
61
62 // evictClosed removes all closed connections from the pool.
63 func (p *Pool) evictClosed() {
64 for url, c := range p.conns {
65 if c.state == StateClosed {
66 delete(p.conns, url)
67 }
68 }
69 }
70