-
Notifications
You must be signed in to change notification settings - Fork 2
/
sender.go
330 lines (294 loc) · 9.37 KB
/
sender.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
package gcm
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
)
const (
// ConnectionServerEndpoint defines the endpoint for the GCM connection server owned by Google.
ConnectionServerEndpoint = "https://android.googleapis.com/gcm/send"
// FCMServerEndpoint defines the endpoint for the FCM connection server by Firebase.
FCMServerEndpoint = "https://fcm.googleapis.com/fcm/send"
// BackoffInitialDelay defines the initial retry interval in milliseconds for exponential backoff.
BackoffInitialDelay = 1000
// MaxBackoffDelay defines the max backoff period in milliseconds.
MaxBackoffDelay = 1024000
)
// GCMEndpoint by default points to the GCM connection server owned by Google,
// but can be otherwise set to a differnet URL if needed (e.g. FCMServerEndpoint).
var GCMEndpoint = ConnectionServerEndpoint
// Sender sends GCM messages to the GCM connection server.
type Sender struct {
// APIKey specifies the API key.
APIKey string
// Client is the http client used for transport. By default it is just http.Client.
Client *http.Client
}
// NewSender instantiates a Sender given the API key.
func NewSender(apiKey string) *Sender {
return NewSenderWithHTTPClient(apiKey, new(http.Client))
}
// NewSenderWithHTTPClient instantiates a Sender given the API key and an http.Client.
func NewSenderWithHTTPClient(apiKey string, client *http.Client) *Sender {
return &Sender{apiKey, client}
}
func checkUnrecoverableErrors(s *Sender, to string, regIDs []string, msg *Message, retries int) error {
// check sender
if s.APIKey == "" {
return fmt.Errorf("missing API key")
}
if s.Client == nil {
s.Client = new(http.Client)
}
// check message
if msg == nil {
return errors.New("message cannot be nil")
}
if msg.TimeToLive < 0 || msg.TimeToLive > 2419200 {
return errors.New("TimeToLive should be non-negative and at most 4 weeks")
}
// check recipients
if to == "" && (regIDs == nil || len(regIDs) <= 0) {
return errors.New("missing recipient(s)")
}
// check retries
if retries < 0 {
return errors.New("retries cannot be negative")
}
return nil
}
type httpError struct {
statusCode int
status string
}
func (e httpError) Error() string {
return fmt.Sprintf("%d error: %s", e.statusCode, e.status)
}
func (s *Sender) sendRaw(msg *message) (*response, error) {
if err := checkUnrecoverableErrors(s, msg.to, msg.registrationIds, &msg.Message, 0); err != nil {
return nil, err
}
msgJSON, err := json.Marshal(msg)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", GCMEndpoint, bytes.NewBuffer(msgJSON))
if err != nil {
return nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("key=%s", s.APIKey))
req.Header.Add("Content-Type", "application/json")
resp, err := s.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
// refer to https://goo.gl/nV1Nf6
// 400: bad json or contains invalid fields
// 401: sender authentication failure
// 5xx: GCM connection server internal error (retry later)
return nil, httpError{resp.StatusCode, resp.Status}
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
response := new(response)
err = json.Unmarshal(body, response)
if err != nil {
log.Printf("failed to unmarshal json: %s", body)
return nil, err
}
return response, nil
}
// SendNoRetry sends a downstream message without retries. The recipient can
// be one of 3 types: single recipient specified with a registration id,
// recipients subscribed to a topic specified with a topic name, members of a
// device group specified with a notification key.
func (s *Sender) SendNoRetry(msg *Message, to string) (*Result, error) {
if err := checkUnrecoverableErrors(s, to, nil, msg, 0); err != nil {
return nil, err
}
rawMsg := &message{Message: *msg, to: to}
resp, err := s.sendRaw(rawMsg)
if err != nil {
return nil, err
}
result := new(Result)
if resp.Results != nil { // downstream message
if len(resp.Results) != 1 {
return nil, fmt.Errorf("invalid response.results: %v", resp.Results)
}
res := resp.Results[0]
result.MessageID = res.MessageID
result.CanonicalRegistrationID = res.RegistrationID
result.Error = res.Err
} else if strings.HasPrefix(to, TopicPrefix) { // topic message
if resp.MessageID != 0 {
result.MessageID = strconv.FormatInt(resp.MessageID, 10)
} else if resp.Err != "" {
result.Error = resp.Err
} else {
return nil, fmt.Errorf("expected message_id or error, but found: %v", *resp)
}
} else { // device group message
result.Success = resp.Success
result.Failure = resp.Failure
result.FailedRegistrationIDs = resp.FailedRegistrationIDs // partial success
}
return result, nil
}
// SendWithRetries sends a downstream message with retries.
func (s *Sender) SendWithRetries(msg *Message, to string, retries int) (result *Result, err error) {
if err := checkUnrecoverableErrors(s, to, nil, msg, retries); err != nil {
return nil, err
}
attempt, backoff := 0, BackoffInitialDelay
for {
attempt++
result, err = s.SendNoRetry(msg, to)
// NOTE: partial success for a device group message is considered successful
tryAgain := false
if attempt <= retries {
if result != nil && (result.Error == ErrorUnavailable || result.Error == ErrorInternalServerError) {
tryAgain = true
} else if err != nil {
if httpErr, isHTTPErr := err.(httpError); isHTTPErr {
tryAgain = httpErr.statusCode >= http.StatusInternalServerError && httpErr.statusCode < 600
}
}
}
if tryAgain {
sleepTime := backoff/2 + rand.Intn(backoff)
time.Sleep(time.Duration(sleepTime) * time.Millisecond)
backoff = min(2*backoff, MaxBackoffDelay)
} else {
break
}
}
return
}
// SendMulticastNoRetry sends a multicast message to multiple recipients without
// retries.
func (s *Sender) SendMulticastNoRetry(msg *Message, registrationIds []string) (*MulticastResult, error) {
if err := checkUnrecoverableErrors(s, "", registrationIds, msg, 0); err != nil {
return nil, err
}
rawMsg := &message{Message: *msg, registrationIds: registrationIds}
resp, err := s.sendRaw(rawMsg)
if err != nil {
return nil, err
}
result := new(MulticastResult)
result.Success = resp.Success
result.Failure = resp.Failure
result.CanonicalIds = resp.CanonicalIds
result.MulticastID = resp.MulticastID
if resp.Results != nil {
result.Results = make([]Result, len(resp.Results))
for i, res := range resp.Results {
result.Results[i] = Result{
MessageID: res.MessageID,
CanonicalRegistrationID: res.RegistrationID,
Error: res.Err,
}
}
}
return result, nil
}
// SendMulticastWithRetries sends a multicast message to the GCM connection
// server, retrying with exponential backoff when the server is unavailable.
// Note that only the following error incidents are retried:
// * 200 + error:Unavailable
// * 200 + error:InternalServerError
// 5xx HTTP status codes are not retried to keep the code simple.
func (s *Sender) SendMulticastWithRetries(msg *Message, regIDs []string, retries int) (*MulticastResult, error) {
if err := checkUnrecoverableErrors(s, "", regIDs, msg, retries); err != nil {
return nil, err
}
rawMsg := &message{Message: *msg, registrationIds: regIDs}
results := make(map[string]result, len(regIDs))
finalResult, backoff, firstResponse := new(MulticastResult), BackoffInitialDelay, true
for {
resp, err := s.sendRaw(rawMsg)
if err != nil {
if httpErr, isHTTPErr := err.(httpError); isHTTPErr && httpErr.statusCode >= 500 && httpErr.statusCode < 600 {
// recoverable error, so continue to retry
} else if firstResponse {
// unrecoverable first response
return nil, err
} else {
// NOTE: unrecoverable error but we had partial results previously,
// so return partial results with nil error.
break
}
}
var retryRegIds []string
if resp != nil {
if resp.MulticastID != 0 {
if firstResponse {
finalResult.MulticastID = resp.MulticastID
} else {
finalResult.RetryMulticastIDs = append(finalResult.RetryMulticastIDs, resp.MulticastID)
}
}
retryRegIds = make([]string, 0, resp.Failure)
for i := range resp.Results {
regID, result := rawMsg.registrationIds[i], resp.Results[i]
results[regID] = result
if result.Err == ErrorUnavailable || result.Err == ErrorInternalServerError {
retryRegIds = append(retryRegIds, regID)
}
}
} else {
retryRegIds = make([]string, len(rawMsg.registrationIds))
for i := range rawMsg.registrationIds {
retryRegIds[i] = rawMsg.registrationIds[i]
}
}
firstResponse = false
if retries <= 0 || len(retryRegIds) == 0 {
break
}
rawMsg.registrationIds = retryRegIds
sleepTime := backoff/2 + rand.Intn(backoff)
time.Sleep(time.Duration(sleepTime) * time.Millisecond)
backoff = min(2*backoff, MaxBackoffDelay)
retries--
}
// reconstruct final results
finalResults := make([]Result, len(regIDs))
for i, regID := range regIDs {
result := results[regID]
finalResults[i] = Result{
MessageID: result.MessageID,
CanonicalRegistrationID: result.RegistrationID,
Error: result.Err,
}
if result.MessageID != "" {
finalResult.Success++
if result.RegistrationID != "" {
finalResult.CanonicalIds++
}
} else {
finalResult.Failure++
}
}
finalResult.Results = finalResults
return finalResult, nil
}
func min(x, y int) int {
if x < y {
return x
}
return y
}