forked from go-pg/pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
117 lines (100 loc) · 2.11 KB
/
listener.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package pg
import (
"log"
"sync"
"time"
)
// Not thread-safe.
type Listener struct {
channels []string
db *DB
_cn *conn
closed bool
mx sync.Mutex
}
func (l *Listener) conn(readTimeout time.Duration) (*conn, error) {
defer l.mx.Unlock()
l.mx.Lock()
if l.closed {
return nil, errListenerClosed
}
if l._cn == nil {
cn, err := l.db.conn()
if err != nil {
return nil, err
}
l._cn = cn
if len(l.channels) > 0 {
if err := l.listen(cn, l.channels...); err != nil {
return nil, err
}
}
}
l._cn.SetReadTimeout(readTimeout)
l._cn.SetWriteTimeout(l.db.opt.WriteTimeout)
return l._cn, nil
}
func (l *Listener) Listen(channels ...string) error {
cn, err := l.conn(l.db.opt.ReadTimeout)
if err != nil {
return err
}
if err := l.listen(cn, channels...); err != nil {
if err != nil {
l.freeConn(err)
}
return err
}
l.channels = append(l.channels, channels...)
return nil
}
func (l *Listener) listen(cn *conn, channels ...string) error {
for _, channel := range channels {
if err := writeQueryMsg(cn.buf, "LISTEN ?", F(channel)); err != nil {
return err
}
}
return cn.FlushWrite()
}
func (l *Listener) Receive() (channel string, payload string, err error) {
return l.ReceiveTimeout(0)
}
func (l *Listener) ReceiveTimeout(readTimeout time.Duration) (channel, payload string, err error) {
channel, payload, err = l.receiveTimeout(readTimeout)
if err != nil {
l.freeConn(err)
}
return channel, payload, err
}
func (l *Listener) receiveTimeout(readTimeout time.Duration) (channel, payload string, err error) {
cn, err := l.conn(readTimeout)
if err != nil {
return "", "", err
}
return readNotification(cn)
}
func (l *Listener) freeConn(err error) (retErr error) {
if err != nil {
if !canRetry(err) {
return nil
}
log.Printf("pg: discarding bad listener connection: %s", err)
}
l.mx.Lock()
if l._cn != nil {
retErr = l.db.pool.Remove(l._cn)
l._cn = nil
}
l.mx.Unlock()
return retErr
}
func (l *Listener) Close() error {
l.mx.Lock()
closed := l.closed
l.closed = true
l.mx.Unlock()
if closed {
return errListenerClosed
}
return l.freeConn(nil)
}