oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package push
2
3import (
4 "context"
5 "errors"
6 "strings"
7 "time"
8
9 "gorm.io/gorm"
10)
11
12// Sender drains the outbox through a Transport. Write runs one write
13// transaction; Check re-checks, inside it, that the person is on the
14// roster and the device credential is still valid: nil, ErrGone (the
15// registration is deleted), ErrNotCurrent (the row is dropped, the
16// registration kept) or a lookup error (the row is tried again later).
17type Sender struct {
18 Write func(context.Context, func(*gorm.DB) error) error
19 Transport Transport
20 Check func(tx *gorm.DB, person, credential string) error
21 Box Box
22 Now func() time.Time
23 // Timeout bounds one send; zero is SendTimeout.
24 Timeout time.Duration
25 // Errorf reports what a pass could not do; never a token or payload.
26 Errorf func(msg string, args ...any)
27}
28
29// Sending limits: rows a pass reads, how long a claim holds, one send's
30// deadline, the retry backoff and the attempts before a row fails, Apple's
31// own trouble's first wait, and how long ended rows are kept.
32const (
33 PassSize = 50
34 Lease = time.Minute
35 SendTimeout = 30 * time.Second
36 FirstRetry = 5 * time.Second
37 MaxRetry = 10 * time.Minute
38 MaxAttempts = 8
39 AppleRetry = 15 * time.Minute
40 Keep = 7 * 24 * time.Hour
41)
42
43// Backoff is the wait before attempt n+1 (n sends have failed).
44func Backoff(n int) time.Duration {
45 d := FirstRetry
46 for i := 1; i < n && d < MaxRetry; i++ {
47 d *= 2
48 }
49 return min(d, MaxRetry)
50}
51
52// What the sender does with a row after a send.
53const (
54 ActSent = "sent" // Apple accepted it
55 ActRetry = "retry" // try again after Wait, an attempt counted
56 ActHold = "hold" // the platform asked to wait Wait; not an attempt
57 ActGone = "gone" // Apple says the token is gone: forget it, fail
58 ActFail = "fail" // never retried: a bug in the request or a refusal
59)
60
61// Verdict is what a send's answer means for its row: the action, the
62// wait before the next try, whether the device's other rows wait too
63// (Apple throttling that device), and whether the pass stops (the
64// platform is paused, over its rate or unavailable: every other row would
65// be refused the same).
66type Verdict struct {
67 Act string
68 Wait time.Duration
69 Device bool
70 Stop bool
71}
72
73// Judge reads one send's answer (the CARLOS verb's, platform-push-
74// submission design §4.2), n being the attempts already made.
75func Judge(res Result, err error, n int) Verdict {
76 switch {
77 case err != nil:
78 return Verdict{Act: ActRetry, Wait: Backoff(n + 1)}
79 case !res.Apple():
80 if res.Refused == 429 || res.Refused == 503 {
81 return Verdict{Act: ActHold, Wait: max(res.RetryAfter, time.Second), Stop: true}
82 }
83 // 400 BAD_REQUEST or PAYLOAD_TOO_LARGE, 401, 403 TOPIC_NOT_ALLOWED
84 // or ENVIRONMENT_NOT_ARMED: retrying sends the same refusal.
85 return Verdict{Act: ActFail}
86 case res.Status >= 200 && res.Status < 300:
87 return Verdict{Act: ActSent}
88 case res.Gone():
89 return Verdict{Act: ActGone}
90 case res.Status == 429:
91 return Verdict{Act: ActRetry, Wait: Backoff(n + 1), Device: true}
92 case res.Status >= 500:
93 // Apple's guidance: not at once, after 15 minutes, then backoff.
94 return Verdict{Act: ActRetry, Wait: AppleRetry << min(n, 3)}
95 }
96 return Verdict{Act: ActFail}
97}
98
99// Drain sends every due row once, and reports how many Apple accepted.
100func (s *Sender) Drain(ctx context.Context) (sent int, err error) {
101 now := s.Now()
102 var due []OutboxRecord
103 err = s.Write(ctx, func(tx *gorm.DB) error {
104 if err := tx.Where("state <> ? AND updated_at < ?", StatePending, now.Add(-Keep)).Delete(&OutboxRecord{}).Error; err != nil {
105 return err
106 }
107 return tx.Where("state = ? AND next_at <= ? AND (lease_until IS NULL OR lease_until < ?)", StatePending, now, now).Order("next_at, created_at, id").Limit(PassSize).Find(&due).Error
108 })
109 if err != nil {
110 return 0, err
111 }
112 for _, r := range due {
113 if ctx.Err() != nil {
114 return sent, ctx.Err()
115 }
116 v, err := s.one(ctx, r)
117 if err != nil {
118 s.errorf("push not sent", "id", r.ID, "err", err)
119 }
120 if v.Act == ActSent {
121 sent++
122 }
123 if v.Stop {
124 break
125 }
126 }
127 return sent, nil
128}
129
130// one claims a row, sends it and records the answer.
131func (s *Sender) one(ctx context.Context, r OutboxRecord) (Verdict, error) {
132 var m Message
133 claimed := false
134 err := s.Write(ctx, func(tx *gorm.DB) error {
135 now := s.Now()
136 held, err := platformHeld(tx, now)
137 if err != nil || held {
138 return err
139 }
140 res := tx.Model(&OutboxRecord{}).Where("id = ? AND state = ? AND next_at <= ? AND (lease_until IS NULL OR lease_until < ?)", r.ID, StatePending, now, now).Select("lease_until").Updates(map[string]any{"lease_until": now.Add(Lease)})
141 if res.Error != nil || res.RowsAffected != 1 {
142 return res.Error
143 }
144 // A coalescing write or another sender may have changed this row
145 // since Drain read its batch. Use the row we just claimed.
146 if err := tx.Where("id = ?", r.ID).Take(&r).Error; err != nil {
147 return err
148 }
149 if !now.Before(Expiration(r.Kind, r.CreatedAt)) {
150 return finish(tx, r.ID, StateDropped, Result{Reason: "expired"}, now)
151 }
152 if err := s.Check(tx, r.Person, r.Credential); err != nil {
153 switch {
154 case errors.Is(err, ErrGone):
155 // Revoked or removed: never sent, and the device forgotten.
156 if err := ForgetCredential(tx, r.Credential); err != nil {
157 return err
158 }
159 return finish(tx, r.ID, StateDropped, Result{Reason: "not_current"}, now)
160 case errors.Is(err, ErrNotCurrent):
161 return finish(tx, r.ID, StateDropped, Result{Reason: "not_current"}, now)
162 }
163 // A lookup failed: the claim lapses and a later pass tries.
164 return err
165 }
166 token, env, err := s.token(tx, r)
167 if errors.Is(err, ErrNoActivity) {
168 if r.Kind == KindActivityEnd {
169 // An end is created after its start and updates, with the
170 // same lifetime. Wait to expiry, without spending delivery
171 // attempts, so an Apple-delayed start can still be ended.
172 wait := min(max(FirstRetry, now.Sub(r.CreatedAt)), MaxRetry)
173 wait = min(wait, Expiration(r.Kind, r.CreatedAt).Sub(now))
174 return retry(tx, r, now, wait, false, Result{Reason: "no_token"})
175 }
176 return finish(tx, r.ID, StateDropped, Result{Reason: "no_token"}, now)
177 }
178 if errors.Is(err, errUnreadableToken) {
179 return finish(tx, r.ID, StateFailed, Result{Reason: "unreadable_token"}, now)
180 }
181 if err != nil {
182 return err
183 }
184 payload, err := s.Box.OpenPayload(r.Payload)
185 if err != nil {
186 return finish(tx, r.ID, StateFailed, Result{Reason: "unreadable_payload"}, now)
187 }
188 if len(payload) > MaxPayload {
189 return finish(tx, r.ID, StateFailed, Result{Reason: "payload_too_large"}, now)
190 }
191 claimed = true
192 m = Message{ID: r.ID, Token: token, Environment: env, Topic: TopicFor(r.PushType), PushType: r.PushType, Priority: r.Priority, CollapseID: r.CollapseID, Expiration: Expiration(r.Kind, r.CreatedAt), Payload: []byte(payload)}
193 return nil
194 })
195 if err != nil || !claimed {
196 return Verdict{}, err
197 }
198 timeout := s.Timeout
199 if timeout <= 0 {
200 timeout = SendTimeout
201 }
202 sendCtx, cancel := context.WithTimeout(ctx, timeout)
203 result, sendErr := s.Transport.Send(sendCtx, m)
204 cancel()
205 if sendErr != nil {
206 sendErr = scrubbed(sendErr, m.Token)
207 }
208 result.Reason = scrub(result.Reason, m.Token)
209 result.Code = scrub(result.Code, m.Token)
210 v := Judge(result, sendErr, r.Attempts)
211 err = s.Write(context.WithoutCancel(ctx), func(tx *gorm.DB) error {
212 now := s.Now()
213 switch v.Act {
214 case ActHold:
215 if err := holdPlatform(tx, now.Add(v.Wait)); err != nil {
216 return err
217 }
218 return retry(tx, r, now, v.Wait, false, result)
219 case ActRetry:
220 if v.Device {
221 // Apple throttles this device: its other rows wait too.
222 if err := tx.Model(&OutboxRecord{}).Where("credential = ? AND state = ? AND lease_until IS NULL AND next_at < ?", r.Credential, StatePending, now.Add(v.Wait)).Select("next_at").Updates(map[string]any{"next_at": now.Add(v.Wait)}).Error; err != nil {
223 return err
224 }
225 }
226 if r.Attempts+1 >= MaxAttempts {
227 return finish(tx, r.ID, StateFailed, result, now)
228 }
229 return retry(tx, r, now, v.Wait, true, result)
230 case ActGone:
231 if err := s.forgetToken(tx, r, m.Token, result.Timestamp); err != nil {
232 return err
233 }
234 return finish(tx, r.ID, StateFailed, result, now)
235 case ActSent:
236 if r.Kind == KindActivityEnd {
237 if err := s.forgetToken(tx, r, m.Token, time.Time{}); err != nil {
238 return err
239 }
240 }
241 return finish(tx, r.ID, StateSent, result, now)
242 }
243 return finish(tx, r.ID, StateFailed, result, now)
244 })
245 if sendErr != nil && err == nil {
246 err = sendErr
247 }
248 return v, err
249}
250
251// scrub takes a token out of text a transport gave back.
252func scrub(text, token string) string {
253 if token == "" || text == "" {
254 return text
255 }
256 i := strings.Index(strings.ToLower(text), strings.ToLower(token))
257 for i >= 0 {
258 text = text[:i] + "[token]" + text[i+len(token):]
259 i = strings.Index(strings.ToLower(text), strings.ToLower(token))
260 }
261 return text
262}
263
264// scrubbed is a transport's error with the token taken out of its text;
265// only the text survives, never the error's own fields.
266func scrubbed(err error, token string) error {
267 return errors.New(scrub(err.Error(), token))
268}
269
270// token is the row's token as the device registered it now, opened.
271func (s *Sender) token(tx *gorm.DB, r OutboxRecord) (token, env string, err error) {
272 var reg Registration
273 if err := tx.Where("credential = ? AND person = ?", r.Credential, r.Person).Take(&reg).Error; err != nil {
274 if errors.Is(err, gorm.ErrRecordNotFound) {
275 return "", "", ErrNoActivity
276 }
277 return "", "", err
278 }
279 sealed := reg.Token
280 switch r.Target {
281 case TargetStart:
282 if reg.StartToken == "" {
283 return "", "", ErrNoActivity
284 }
285 sealed = reg.StartToken
286 case TargetActivity:
287 var a ActivityToken
288 err := tx.Where("credential = ? AND task_id = ?", r.Credential, r.TaskID).Take(&a).Error
289 if errors.Is(err, gorm.ErrRecordNotFound) {
290 return "", "", ErrNoActivity
291 }
292 if err != nil {
293 return "", "", err
294 }
295 sealed = a.Token
296 }
297 token, err = s.Box.open(domainToken, sealed)
298 if err != nil {
299 return "", "", errUnreadableToken
300 }
301 return token, reg.Environment, nil
302}
303
304// retry puts a row back for wait, keeping the answer if there was one;
305// counted, it was an attempt.
306func retry(tx *gorm.DB, r OutboxRecord, now time.Time, wait time.Duration, counted bool, res Result) error {
307 attempts := r.Attempts
308 if counted {
309 attempts++
310 }
311 return tx.Model(&OutboxRecord{}).Where("id = ?", r.ID).Select("attempts", "next_at", "lease_until", "updated_at", "status", "reason").Updates(map[string]any{"attempts": attempts, "next_at": now.Add(wait), "lease_until": nil, "updated_at": now, "status": res.Status, "reason": reasonOf(res)}).Error
312}
313
314// reasonOf is what a row keeps of an answer: Apple's reason, else the
315// platform's code.
316func reasonOf(res Result) string {
317 if res.Reason != "" {
318 return res.Reason
319 }
320 return res.Code
321}
322
323func finish(tx *gorm.DB, id, state string, res Result, now time.Time) error {
324 fields := map[string]any{"state": state, "status": res.Status, "reason": reasonOf(res), "apns_id": res.APNsID, "lease_until": nil, "updated_at": now, "attempts": gorm.Expr("attempts + 1")}
325 if state == StateSent {
326 fields["sent_at"] = now
327 }
328 if state == StateDropped {
329 fields["attempts"] = gorm.Expr("attempts")
330 }
331 keys := make([]string, 0, len(fields))
332 for k := range fields {
333 keys = append(keys, k)
334 }
335 return tx.Model(&OutboxRecord{}).Where("id = ?", id).Select(keys).Updates(fields).Error
336}
337
338func (s *Sender) errorf(msg string, args ...any) {
339 if s.Errorf != nil {
340 s.Errorf(msg, args...)
341 }
342}
343
344// Serve drains the outbox every interval and at each wake, until ctx ends.
345func (s *Sender) Serve(ctx context.Context, wake <-chan struct{}, every time.Duration) {
346 tick := time.NewTicker(every)
347 defer tick.Stop()
348 for {
349 if _, err := s.Drain(ctx); err != nil && ctx.Err() == nil {
350 s.errorf("push outbox not drained", "err", err)
351 }
352 select {
353 case <-ctx.Done():
354 return
355 case <-tick.C:
356 case <-wake:
357 }
358 }
359}
360