Repository navigation
Expand file tree
/
Copy pathhttp_notification_sender.go
More file actions
265 lines (230 loc) · 7.26 KB
/
Copy pathhttp_notification_sender.go
File metadata and controls
265 lines (230 loc) · 7.26 KB
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
package services
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
"firebase.google.com/go/messaging"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
"github.com/NdoleStudio/stacktrace"
"github.com/avast/retry-go/v5"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
const (
maxNotificationResponseDiscardBytes = 4 * 1024
notificationHTTPAttempts = 3
notificationHTTPTimeout = 5 * time.Second
notificationHTTPRetryDelay = 250 * time.Millisecond
notificationJWTIssuer = "api.httpsms.com"
notificationJWTValidity = 10 * time.Minute
)
// HTTPNotificationSender sends FCM-compatible gateway notifications to HTTPS adapters.
type HTTPNotificationSender struct {
logger telemetry.Logger
client *http.Client
retrier *retry.Retrier
timeout time.Duration
}
var _ FCMClient = (*HTTPNotificationSender)(nil)
// NewHTTPNotificationSender creates an HTTP notification sender.
func NewHTTPNotificationSender(
logger telemetry.Logger,
client *http.Client,
) *HTTPNotificationSender {
return newHTTPNotificationSenderWithRetrier(
logger,
client,
newHTTPNotificationRetrier(notificationHTTPRetryDelay),
)
}
func newHTTPNotificationSenderWithRetrier(
logger telemetry.Logger,
client *http.Client,
retrier *retry.Retrier,
) *HTTPNotificationSender {
return &HTTPNotificationSender{
logger: logger,
client: client,
retrier: retrier,
timeout: notificationHTTPTimeout,
}
}
// Send delivers a notification to an HTTPS adapter. A successful response only accepts wake-up delivery.
func (sender *HTTPNotificationSender) Send(
ctx context.Context,
message *messaging.Message,
phoneID uuid.UUID,
) (string, error) {
if message == nil {
return "", sender.notificationError("", "notification message is nil")
}
endpoint, err := url.Parse(message.Token)
if err != nil {
return "", sender.notificationError("", "cannot parse notification endpoint")
}
hostname := endpoint.Hostname()
body, err := encodeHTTPNotificationPayload(message)
if err != nil {
return "", sender.notificationError(hostname, "cannot encode notification")
}
authToken, err := sender.getAuthToken(endpoint, phoneID)
if err != nil {
return "", sender.notificationError(hostname, "cannot generate notification auth token")
}
err = sender.retrier.Do(func() error {
return sender.deliver(ctx, endpoint, body, authToken)
})
if err == nil {
return "http/success", nil
}
if ctx.Err() != nil {
return "", sender.notificationError(hostname, "notification request cancelled")
}
return "", sender.notificationError(hostname, "notification request failed")
}
// getAuthToken generates a JWT bearer token for the HTTPS adapter, signed with the phone ID
// the same way webhook requests are signed with the webhook signing key. The phone ID is only
// used as the HMAC secret and is intentionally not embedded in any claim: the adapter already
// knows which phone ID to verify against from its own gateway registration, and putting the
// phone ID in a readable claim would let anyone who intercepts one token read the signing
// secret and forge further tokens.
func (sender *HTTPNotificationSender) getAuthToken(endpoint *url.URL, phoneID uuid.UUID) (string, error) {
audience := *endpoint
audience.User = nil
now := time.Now().UTC()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.RegisteredClaims{
Audience: []string{audience.String()},
ExpiresAt: jwt.NewNumericDate(now.Add(notificationJWTValidity)),
IssuedAt: jwt.NewNumericDate(now),
Issuer: notificationJWTIssuer,
NotBefore: jwt.NewNumericDate(now.Add(-notificationJWTValidity)),
})
return token.SignedString([]byte(phoneID.String()))
}
func encodeHTTPNotificationPayload(message *messaging.Message) ([]byte, error) {
return json.Marshal(map[string]any{
"message": message,
})
}
func (sender *HTTPNotificationSender) deliver(
ctx context.Context,
endpoint *url.URL,
body []byte,
authToken string,
) error {
if err := ctx.Err(); err != nil {
return terminalNotificationRequestError{cause: err}
}
attemptCtx, cancel := context.WithTimeout(ctx, sender.timeout)
defer cancel()
request, err := createHTTPNotificationRequest(attemptCtx, endpoint, body, authToken)
if err != nil {
return terminalNotificationRequestError{cause: err}
}
err = sender.sendAttempt(request)
if ctx.Err() != nil {
return terminalNotificationRequestError{cause: ctx.Err()}
}
return err
}
func createHTTPNotificationRequest(
ctx context.Context,
endpoint *url.URL,
body []byte,
authToken string,
) (*http.Request, error) {
request, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
endpoint.String(),
bytes.NewReader(body),
)
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authToken))
return request, nil
}
func (sender *HTTPNotificationSender) sendAttempt(request *http.Request) error {
response, err := sender.client.Do(request)
if err != nil {
return err
}
if response.Body != nil {
_, _ = io.CopyN(io.Discard, response.Body, maxNotificationResponseDiscardBytes)
_ = response.Body.Close()
}
if response.StatusCode >= http.StatusOK && response.StatusCode < http.StatusMultipleChoices {
return nil
}
if isRetryableNotificationStatus(response.StatusCode) {
return retryableNotificationStatusError{statusCode: response.StatusCode}
}
return terminalNotificationStatusError{statusCode: response.StatusCode}
}
func newHTTPNotificationRetrier(delay time.Duration) *retry.Retrier {
return retry.New(
retry.Attempts(notificationHTTPAttempts),
retry.Delay(delay),
retry.DelayType(retry.BackOffDelay),
retry.LastErrorOnly(true),
retry.RetryIf(isRetryableNotificationError),
)
}
func (sender *HTTPNotificationSender) notificationError(hostname string, message string) error {
if hostname == "" {
hostname = "unknown"
}
err := stacktrace.Propagatef(stacktrace.NewErrorf("%s", message), "cannot send notification to [%s]", hostname)
if sender.logger != nil {
sender.logger.Error(err)
}
return err
}
func isRetryableNotificationStatus(statusCode int) bool {
return statusCode == http.StatusRequestTimeout ||
statusCode == http.StatusTooManyRequests ||
(statusCode >= http.StatusInternalServerError && statusCode < 600)
}
type retryableNotificationStatusError struct {
statusCode int
}
func (error retryableNotificationStatusError) Error() string {
return http.StatusText(error.statusCode)
}
type terminalNotificationStatusError struct {
statusCode int
}
func (error terminalNotificationStatusError) Error() string {
return http.StatusText(error.statusCode)
}
type terminalNotificationRequestError struct {
cause error
}
func (notificationError terminalNotificationRequestError) Error() string {
return notificationError.cause.Error()
}
func (notificationError terminalNotificationRequestError) Unwrap() error {
return notificationError.cause
}
func isRetryableNotificationError(err error) bool {
if err == nil || isTerminalNotificationError(err) {
return false
}
return true
}
func isTerminalNotificationError(err error) bool {
var statusError terminalNotificationStatusError
if errors.As(err, &statusError) {
return true
}
var requestError terminalNotificationRequestError
return errors.As(err, &requestError)
}