-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
277 lines (252 loc) · 7.21 KB
/
main.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
package main
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"strconv"
"time"
"cloud.google.com/go/datastore"
"golang.org/x/net/http2"
)
type Device struct {
ApiVersion int `datastore:"api_version,noindex"`
App string `datastore:"app"`
Created time.Time `datastore:"created,noindex"`
DeviceId string `datastore:"device_id,noindex"`
DeviceInfo string `datastore:"device_info,noindex"`
Environment string `datastore:"environment,noindex"`
Failures int `datastore:"failures,noindex"`
LastSuccess time.Time `datastore:"last_success,noindex"`
Platform string `datastore:"platform,noindex"`
Token string `datastore:"token"`
TotalFailures int `datastore:"total_failures,noindex"`
TotalSuccesses int `datastore:"total_successes,noindex"`
Updated time.Time `datastore:"updated,noindex"`
}
type Payload struct {
AccountID int64 `json:"account_id"`
App string `json:"app"`
Data json.RawMessage `json:"data"`
DeviceToken string `json:"device_token"`
Environment string `json:"environment"`
}
type PushError struct {
Body []byte
StatusCode int
}
func (pe PushError) Error() string {
return fmt.Sprintf("HTTP %d (%s)", pe.StatusCode, pe.Body)
}
func (pe PushError) Permanent() bool {
return pe.StatusCode == 400 || pe.StatusCode == 410
}
func (pe PushError) Retryable() bool {
return pe.StatusCode == 429 || pe.StatusCode == 500 || pe.StatusCode == 503
}
type ClientMap map[string]*http.Client
func (m ClientMap) Create(app string) *http.Client {
if _, ok := m[app]; ok {
panic("tried to overwrite existing client")
}
client := NewClient(app)
m[app] = client
return client
}
var (
store *datastore.Client
clients = make(ClientMap)
ctx = context.Background()
timestamp = time.Now()
)
const (
ProjectId = "roger-api"
AppleHost = "https://api.push.apple.com"
AppleHostDev = "https://api.development.push.apple.com"
DefaultPort = "8080"
MaxRetries = 3
PingFrequency = time.Second
PingThreshold = time.Minute
)
func main() {
// Set up the Datastore client.
var err error
store, err = datastore.NewClient(ctx, ProjectId)
if err != nil {
log.Fatalf("Failed to create Datastore client (datastore.NewClient: %v)", err)
}
// Set up the APNS clients.
clients.Create("cam.reaction.ReactionCam")
port := DefaultPort
if s := os.Getenv("PORT"); s != "" {
port = s
}
http.HandleFunc("/ping", pingHandler)
http.HandleFunc("/v1/push", pushHandler)
go pinger()
// Set up the server.
log.Printf("Serving on %s...", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatalf("http.ListenAndServe: %v", err)
}
}
func NewClient(app string) *http.Client {
cert, err := tls.LoadX509KeyPair(
fmt.Sprintf("secrets/%s.pem", app),
fmt.Sprintf("secrets/%s.key", app))
if err != nil {
log.Fatalf("Failed to create client for %s: %v", app, err)
}
config := &tls.Config{
Certificates: []tls.Certificate{cert},
}
config.BuildNameToCertificate()
transport := &http.Transport{
TLSClientConfig: config,
}
// Explicitly enable HTTP/2 as TLS-configured clients don't auto-upgrade.
// See: https://github.com/golang/go/issues/14275
if err := http2.ConfigureTransport(transport); err != nil {
log.Fatalf("Failed to configure HTTP/2 for %s client: %v", app, err)
}
return &http.Client{
Timeout: 3 * time.Second,
Transport: transport,
}
}
func Push(app, deviceToken, env string, data json.RawMessage) (err error) {
client, ok := clients[app]
if !ok {
err = fmt.Errorf("invalid app \"%s\"", app)
return
}
var url string
if env == "development" {
url = fmt.Sprintf("%s/3/device/%s", AppleHostDev, deviceToken)
} else {
url = fmt.Sprintf("%s/3/device/%s", AppleHost, deviceToken)
}
req, err := http.NewRequest("POST", url, bytes.NewReader(data))
if err != nil {
return
}
expiration := time.Now().Add(168 * time.Hour).Unix()
req.Header.Set("apns-expiration", strconv.FormatInt(expiration, 10))
req.Header.Set("apns-topic", app)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
timestamp = time.Now()
if resp.StatusCode == http.StatusOK {
return nil
}
// Something went wrong – get the error from body.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return PushError{Body: body, StatusCode: resp.StatusCode}
}
func pinger() {
// TODO: Figure out how to ping connections instead of closing.
for {
if time.Since(timestamp) > PingThreshold {
timestamp = time.Now()
for app := range clients {
clients[app] = NewClient(app)
}
}
time.Sleep(PingFrequency)
}
}
// Push with retry.
func push(payload Payload) {
app := payload.App
if app == "" {
log.Printf("Unrecognized app %#v", app)
return
}
accountKey := datastore.IDKey("Account", payload.AccountID, nil)
deviceKey := datastore.NameKey("Device", payload.DeviceToken, accountKey)
attempt := 1
for {
err := Push(app, payload.DeviceToken, payload.Environment, payload.Data)
if err, ok := err.(PushError); ok && err.Permanent() {
if err.Permanent() {
log.Printf("[%d] PERMANENT FAILURE: %s", payload.AccountID, err)
if err := store.Delete(ctx, deviceKey); err != nil {
log.Printf("[%d] FAILED TO DELETE TOKEN: %v", payload.AccountID, err)
}
} else if !err.Retryable() {
log.Printf("[%d] DROPPING NOTIFICATION: %s", payload.AccountID, err)
}
log.Printf("[%d] %s", payload.AccountID, string(payload.Data))
return
}
if updateErr := updateDeviceStats(ctx, deviceKey, err == nil); updateErr != nil {
log.Printf("[%d] FAILED TO UPDATE TOKEN: %v", payload.AccountID, updateErr)
}
if err == nil {
return
}
// An error occurred.
log.Printf("[%d] Failed to push (attempt %d/%d): %s", payload.AccountID, attempt, MaxRetries, err)
// Exponential backoff.
if attempt >= MaxRetries {
log.Printf("[%d] DROPPING NOTIFICATION: exceeded max retries", payload.AccountID)
log.Printf("[%d] %s", payload.AccountID, string(payload.Data))
return
}
time.Sleep(time.Duration(math.Exp2(float64(attempt-1))) * time.Second)
attempt += 1
}
}
func updateDeviceStats(ctx context.Context, key *datastore.Key, success bool) error {
_, err := store.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
var device Device
if err := tx.Get(key, &device); err != nil {
return err
}
now := time.Now()
device.Updated = now
if success {
device.LastSuccess = now
device.TotalSuccesses += 1
device.Failures = 0
} else {
device.Failures += 1
device.TotalFailures += 1
}
_, err := tx.Put(key, &device)
return err
})
return err
}
func pingHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
fmt.Fprintln(w, "ok")
}
func pushHandler(w http.ResponseWriter, r *http.Request) {
scanner := bufio.NewScanner(r.Body)
for scanner.Scan() {
var payload Payload
if err := json.Unmarshal(scanner.Bytes(), &payload); err != nil {
log.Printf("Failed to parse JSON: %s | %s", err, scanner.Text())
continue
}
go push(payload)
}
if err := scanner.Err(); err != nil {
log.Printf("Failed to read data: %s", err)
}
}