-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparsepush.go
362 lines (324 loc) · 8.32 KB
/
parsepush.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// Package parsepush provides a client for receiving pushes from the Parse Push
// API. This is useful for building services that can receive pushes. With Go
// being usable on certain embedded devices, this can serve as a useful library
// for IoT devices.
package parsepush
import (
"bufio"
"crypto/tls"
"encoding/json"
"errors"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/facebookgo/clock"
)
const (
defaultAddr = "push.parse.com:443"
defaultPingInterval = time.Minute
defaultDialerTimeout = time.Minute
defaultRetryInterval = 10 * time.Second
)
var (
errMissingApplicationID = errors.New("parsepush: missing Application ID")
errMissingInstallationID = errors.New("parsepush: missing Installation ID")
errMissingPushHandler = errors.New("parsepush: missing Push Handler")
pingMessage = []byte("{}\r\n")
)
// A Conn is a connection receiving pushes from Parse.
type Conn struct {
addr string
tlsConfig *tls.Config
dialer *net.Dialer
pingInterval time.Duration
installationID string
applicationID string
lastHash atomic.Value
pushHandler func([]byte)
errHandler func(error)
retry func(int) time.Duration
closeOnce sync.Once
closeChan chan chan struct{}
// for testing purposes
clock clock.Clock
dialF func(*net.Dialer, string, string, *tls.Config) (net.Conn, error)
}
func (c *Conn) handleErr(err error) {
if err != nil && c.errHandler != nil {
c.errHandler(err)
}
}
// dial returns a conn if possible. it will return nil if a conn has not been
// established yet and we're closing down.
func (c *Conn) dial() net.Conn {
ir := map[string]string{
"installation_id": c.installationID,
"oauth_key": c.applicationID,
"v": "e1.0.0",
}
if lastHash := c.LastHash(); lastHash != "" {
ir["last"] = lastHash
}
irb, _ := json.Marshal(ir)
irb = append(irb, '\r', '\n')
attempt := 0
for {
conn, err := c.dialF(c.dialer, "tcp", c.addr, c.tlsConfig)
// successfully dialed out. tell parse who we are and return the prepped
// connection.
if err == nil {
_, err = conn.Write(irb)
if err == nil {
return conn
}
}
// failed to dial, log and wait some time before we retry, give up only if
// we are closing down.
c.handleErr(err)
select {
case <-c.clock.After(c.retry(attempt)):
case done := <-c.closeChan:
close(done)
return nil
}
attempt++
}
}
func (c *Conn) do() {
var lr lineReader
var conn net.Conn
pingTicker := c.clock.Ticker(c.pingInterval)
defer pingTicker.Stop()
handleErr := func(err error) {
if err != nil {
c.handleErr(err)
conn.Close()
close(lr.close)
conn = nil
<-lr.done
}
}
for {
// we may be connecting the first time around, or trying to reconnect if we
// lost our connection.
if conn == nil {
conn = c.dial()
if conn == nil {
// this can happen if we close before we successfully dial out.
return
}
lr.reader = conn
lr.lines = make(chan []byte)
lr.errch = make(chan error)
lr.close = make(chan struct{})
lr.done = make(chan struct{})
go lr.read()
}
select {
case push := <-lr.lines:
c.pushHandler(push)
case err := <-lr.errch:
handleErr(err)
case <-pingTicker.C:
_, err := conn.Write(pingMessage)
handleErr(err)
case done := <-c.closeChan:
conn.Close()
close(lr.close)
<-lr.done
close(done)
return
}
}
}
// LastHash returns the hash of the last push we received, if available.
func (c *Conn) LastHash() string {
v, _ := c.lastHash.Load().(string)
return v
}
// Close closes the underlying connection and stops receiving pushes.
func (c *Conn) Close() error {
c.closeOnce.Do(func() {
done := make(chan struct{})
c.closeChan <- done
<-done
})
return nil
}
// ConnOption allows configuring various aspects of the Conn.
type ConnOption func(*Conn) error
// ConnAddr configures the parse push server address. If unspecified, it
// defaults to "push.parse.com:443".
func ConnAddr(addr string) ConnOption {
return func(c *Conn) error {
c.addr = addr
return nil
}
}
// ConnTLSConfig configures TLS options. Defaults to nil.
func ConnTLSConfig(config *tls.Config) ConnOption {
return func(c *Conn) error {
c.tlsConfig = config
return nil
}
}
// ConnDialer configures a Dialer. This allows for configuring timeouts etc.
// The default dialer has a 1 minute timeout.
func ConnDialer(dialer *net.Dialer) ConnOption {
return func(c *Conn) error {
c.dialer = dialer
return nil
}
}
// ConnPingInterval configures the interval at which we send a ping on the
// connection. Defaults to 1 minute.
func ConnPingInterval(interval time.Duration) ConnOption {
return func(c *Conn) error {
c.pingInterval = interval
return nil
}
}
// ConnApplicationID configures the application ID. This is required for a
// connection.
func ConnApplicationID(id string) ConnOption {
return func(c *Conn) error {
c.applicationID = id
return nil
}
}
// ConnInstallationID configures the installation ID we're receiving pushes
// for. This is required for a connection.
func ConnInstallationID(id string) ConnOption {
return func(c *Conn) error {
c.installationID = id
return nil
}
}
// ConnLastHash configures the hash of the last successful push we received.
// This ensures we don't miss any relevant pushes since the last disconnect.
func ConnLastHash(hash string) ConnOption {
return func(c *Conn) error {
c.lastHash.Store(hash)
return nil
}
}
// ConnPushHandler configures the function that will be invoked when a push
// arrives. The push handler is invoked synchronously so you should not perform
// long running operations in this callback.
func ConnPushHandler(handler func([]byte)) ConnOption {
return func(c *Conn) error {
c.pushHandler = handler
return nil
}
}
// ConnErrorHandler configures an optional error handler. In the face of
// errors, we keep retrying. Configuring an error handler lets you process the
// ignored errors.
func ConnErrorHandler(handler func(error)) ConnOption {
return func(c *Conn) error {
c.errHandler = handler
return nil
}
}
// ConnRetryStrategy configures an optional retry strategy. The configured
// function is given the attempt number and must return the delay duration
// before which a reconnect will be attempted.
//
// https://godoc.org/aqwari.net/retry provides an excellent set of strategies.
func ConnRetryStrategy(s func(nth int) time.Duration) ConnOption {
return func(c *Conn) error {
c.retry = s
return nil
}
}
// NewConn creates a new Conn with the given options. At minimum you need to
// provide ConnApplicationID, ConnInstallationID and ConnPushHandler.
func NewConn(options ...ConnOption) (*Conn, error) {
c := Conn{
clock: clock.New(),
dialF: defaultDialF,
closeChan: make(chan chan struct{}),
}
for _, o := range options {
if err := o(&c); err != nil {
return nil, err
}
}
if c.addr == "" {
c.addr = defaultAddr
}
if c.pingInterval.Nanoseconds() == 0 {
c.pingInterval = defaultPingInterval
}
if c.applicationID == "" {
return nil, errMissingApplicationID
}
if c.installationID == "" {
return nil, errMissingInstallationID
}
if c.pushHandler == nil {
return nil, errMissingPushHandler
}
if c.dialer == nil {
c.dialer = &net.Dialer{
Timeout: defaultDialerTimeout,
}
}
if c.retry == nil {
c.retry = defaultRetry
}
go c.do()
return &c, nil
}
type lineReader struct {
reader io.Reader
lines chan []byte
errch chan error
close chan struct{}
done chan struct{}
}
func (l lineReader) read() {
defer close(l.done)
scanner := bufio.NewScanner(l.reader)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
// scanner.Bytes are only valid until the next call to Scan, so we must
// copy them out.
line := scanner.Bytes()
lineCopy := make([]byte, len(line))
copy(lineCopy, line)
// send our line, unless we're closed
select {
case l.lines <- lineCopy:
case <-l.close:
return
}
}
// either a real error or send io.EOF
err := scanner.Err()
if err == nil {
err = io.EOF
}
// send our error, unless we're closed
select {
case l.errch <- err:
case <-l.close:
}
}
func defaultRetry(int) time.Duration {
return defaultRetryInterval
}
func defaultDialF(
dialer *net.Dialer,
network string,
addr string,
config *tls.Config,
) (c net.Conn, err error) {
c, err = tls.DialWithDialer(dialer, network, addr, config)
if err != nil {
c = nil // remove type info
}
return c, err
}