-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpgbroadcaster.go
95 lines (80 loc) · 2.24 KB
/
pgbroadcaster.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
package pgbroadcaster
import (
"encoding/json"
"fmt"
"time"
"github.com/lib/pq"
)
type pgnotification struct {
Table string `json:"table"`
Action string `json:"action"`
Data map[string]interface{} `json:"data"`
}
type PgBroadcaster struct {
h *hub
l *pq.Listener
}
func NewPgBroadcaster(pgconninfo string) (*PgBroadcaster, error) {
// Create a new hub to manage the connections
var h = hub{
broadcast: make(chan pgnotification),
register: make(chan *connection),
unregister: make(chan *connection),
connections: make(map[*connection]bool),
}
// start the hub in a new go-routine.
go h.run()
// Get a new postgres listener connection
pl, err := newPgListener(pgconninfo)
if err != nil {
fmt.Println("pgbroadcaster: ", err)
return nil, err
}
// Create a PgBroadcaster and start handling connections
pb := &PgBroadcaster{&h, pl}
go pb.handleIncomingNotifications()
// Return the pgBroadcaster
return pb, nil
}
// Listen makes the PgBroadcaster's underlying pglistener listen to thh
// specified channel
func (pb *PgBroadcaster) Listen(pgchannel string) error {
return pb.l.Listen(pgchannel)
}
// newPgListener creates and returns the pglistener from the pq package.
func newPgListener(pgconninfo string) (*pq.Listener, error) {
// create a callback function to monitor connection state changes
pgEventCallback := func(ev pq.ListenerEventType, err error) {
if err != nil {
fmt.Println("pgbroadcast: ", err.Error())
}
}
// create the listener
l := pq.NewListener(pgconninfo, 10*time.Second, time.Minute, pgEventCallback)
return l, nil
}
func (pb *PgBroadcaster) handleIncomingNotifications() {
for {
select {
case n := <-pb.l.Notify:
// For some reason after connection loss with the postgres database,
// the first notifications is a nil notification. Ignore it.
if n == nil {
continue
}
// Unmarshal JSON in pgnotification struct
var pgn pgnotification
err := json.Unmarshal([]byte(n.Extra), &pgn)
if err != nil {
fmt.Println("pgbroadcast: error processing JSON: ", err)
} else {
pb.h.broadcast <- pgn
}
case <-time.After(60 * time.Second):
// received no events for 60 seconds, ping connection")
go func() {
pb.l.Ping()
}()
}
}
}