| 1 | package push |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "log" |
| 9 | "regexp" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "gorm.io/gorm" |
| 16 | "gorm.io/gorm/logger" |
| 17 | ) |
| 18 | |
| 19 | var uuidShape = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) |
| 20 | |
| 21 | // TestRowIDIsAnAPNsID: every row's ID, sent as apns-id, is a canonical |
| 22 | // lowercase UUID (Apple answers 400 BadMessageId to anything else). |
| 23 | func TestRowIDIsAnAPNsID(t *testing.T) { |
| 24 | seen := map[string]bool{} |
| 25 | for range 200 { |
| 26 | id := NewID() |
| 27 | if !uuidShape.MatchString(id) || seen[id] { |
| 28 | t.Fatalf("id %q", id) |
| 29 | } |
| 30 | seen[id] = true |
| 31 | } |
| 32 | r := newRig(t) |
| 33 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 34 | if id := r.rows()[0].ID; !uuidShape.MatchString(id) { |
| 35 | t.Fatalf("row id %q", id) |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | // TestJudge: what each answer of the CARLOS verb (design §4.2) does to |
| 40 | // its row. |
| 41 | func TestJudge(t *testing.T) { |
| 42 | for name, c := range map[string]struct { |
| 43 | res Result |
| 44 | err error |
| 45 | want Verdict |
| 46 | }{ |
| 47 | "delivered": {Result{Status: 200}, nil, Verdict{Act: ActSent}}, |
| 48 | "no answer": {Result{}, errors.New("reset"), Verdict{Act: ActRetry, Wait: Backoff(3)}}, |
| 49 | "Unregistered": {Result{Status: 410, Reason: ReasonUnregistered}, nil, Verdict{Act: ActGone}}, |
| 50 | "ExpiredToken": {Result{Status: 410, Reason: ReasonExpiredToken}, nil, Verdict{Act: ActGone}}, |
| 51 | "BadDeviceToken": {Result{Status: 400, Reason: ReasonBadDeviceToken}, nil, Verdict{Act: ActGone}}, |
| 52 | "DeviceTokenNotForTopic": {Result{Status: 400, Reason: ReasonDeviceTokenNotForTopic}, nil, Verdict{Act: ActGone}}, |
| 53 | "Apple throttles a device": {Result{Status: 429, Reason: "TooManyRequests"}, nil, Verdict{Act: ActRetry, Wait: Backoff(3), Device: true}}, |
| 54 | "Apple 500": {Result{Status: 500}, nil, Verdict{Act: ActRetry, Wait: 4 * AppleRetry}}, |
| 55 | "Apple 503": {Result{Status: 503}, nil, Verdict{Act: ActRetry, Wait: 4 * AppleRetry}}, |
| 56 | "another Apple 4xx": {Result{Status: 400, Reason: "BadCollapseId"}, nil, Verdict{Act: ActFail}}, |
| 57 | "BAD_REQUEST": {Result{Refused: 400, Code: "BAD_REQUEST"}, nil, Verdict{Act: ActFail}}, |
| 58 | "PAYLOAD_TOO_LARGE": {Result{Refused: 400, Code: "PAYLOAD_TOO_LARGE"}, nil, Verdict{Act: ActFail}}, |
| 59 | "401": {Result{Refused: 401}, nil, Verdict{Act: ActFail}}, |
| 60 | "TOPIC_NOT_ALLOWED": {Result{Refused: 403, Code: "TOPIC_NOT_ALLOWED"}, nil, Verdict{Act: ActFail}}, |
| 61 | "ENVIRONMENT_NOT_ARMED": {Result{Refused: 403, Code: "ENVIRONMENT_NOT_ARMED"}, nil, Verdict{Act: ActFail}}, |
| 62 | "PAUSED": {Result{Refused: 429, Code: "PAUSED", RetryAfter: 300 * time.Second}, nil, Verdict{Act: ActHold, Wait: 300 * time.Second, Stop: true}}, |
| 63 | "RATE": {Result{Refused: 429, Code: "RATE", RetryAfter: time.Second}, nil, Verdict{Act: ActHold, Wait: time.Second, Stop: true}}, |
| 64 | "PUSHER_UNAVAILABLE": {Result{Refused: 503, Code: "PUSHER_UNAVAILABLE", RetryAfter: 5 * time.Second}, nil, Verdict{Act: ActHold, Wait: 5 * time.Second, Stop: true}}, |
| 65 | "APNS_UNAVAILABLE": {Result{Refused: 503, Code: "APNS_UNAVAILABLE", RetryAfter: 60 * time.Second}, nil, Verdict{Act: ActHold, Wait: 60 * time.Second, Stop: true}}, |
| 66 | "a platform 410 is not gone": {Result{Refused: 410, Code: "X"}, nil, Verdict{Act: ActFail}}, |
| 67 | "a platform 503 without a code": {Result{Refused: 503, RetryAfter: 5 * time.Second}, nil, Verdict{Act: ActHold, Wait: 5 * time.Second, Stop: true}}, |
| 68 | } { |
| 69 | if got := Judge(c.res, c.err, 2); got != c.want { |
| 70 | t.Errorf("%s: %+v, want %+v", name, got, c.want) |
| 71 | } |
| 72 | } |
| 73 | if Judge(Result{Status: 500}, nil, 0).Wait != AppleRetry { |
| 74 | t.Fatal("Apple's trouble is retried after 15 minutes first") |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | // carlos answers each send as the CARLOS verb would, through CarlosResult. |
| 79 | func (r *rig) carlos(status int, retryAfter, body string) { |
| 80 | r.answer = func(Message) (Result, error) { return CarlosResult(status, retryAfter, []byte(body)) } |
| 81 | } |
| 82 | |
| 83 | // TestSenderCarlosOutcomes: the sender acts on every CARLOS outcome. A |
| 84 | // platform hold (PAUSED, RATE, PUSHER_UNAVAILABLE, APNS_UNAVAILABLE) |
| 85 | // waits its Retry-After without spending an attempt and ends the pass; |
| 86 | // a refusal fails the row; Apple throttling one device holds its other |
| 87 | // rows; Apple's own trouble waits 15 minutes. |
| 88 | func TestSenderCarlosOutcomes(t *testing.T) { |
| 89 | for code, wait := range map[string]time.Duration{"PAUSED": 300 * time.Second, "RATE": time.Second, "PUSHER_UNAVAILABLE": 5 * time.Second, "APNS_UNAVAILABLE": 60 * time.Second} { |
| 90 | r := newRig(t) |
| 91 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 92 | r.enqueue(KindAlert, TargetDevice, "c2", false) |
| 93 | status := 429 |
| 94 | if strings.HasSuffix(code, "UNAVAILABLE") { |
| 95 | status = 503 |
| 96 | } |
| 97 | r.carlos(status, jsonInt(int64(wait/time.Second)), `{"code":"`+code+`"}`) |
| 98 | if r.drain() != 0 || len(r.sent) != 1 { |
| 99 | t.Fatalf("%s: the pass went on after a hold: %d sends", code, len(r.sent)) |
| 100 | } |
| 101 | var row OutboxRecord |
| 102 | r.must(r.d.G.Where("id = ?", r.sent[0].ID).Take(&row).Error) |
| 103 | if row.State != StatePending || row.Attempts != 0 || !row.NextAt.Equal(at.Add(wait)) || row.Reason != code { |
| 104 | t.Fatalf("%s: row %+v", code, row) |
| 105 | } |
| 106 | } |
| 107 | for _, refusal := range []struct { |
| 108 | status int |
| 109 | body string |
| 110 | }{{400, `{"code":"BAD_REQUEST"}`}, {400, `{"code":"PAYLOAD_TOO_LARGE"}`}, {401, "unauthorized\n"}, {403, `{"code":"TOPIC_NOT_ALLOWED"}`}, {403, `{"code":"ENVIRONMENT_NOT_ARMED"}`}} { |
| 111 | r := newRig(t) |
| 112 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 113 | r.carlos(refusal.status, "", refusal.body) |
| 114 | r.drain() |
| 115 | var n int64 |
| 116 | r.d.G.Model(&Registration{}).Count(&n) |
| 117 | if row := r.rows()[0]; row.State != StateFailed || n != 1 { |
| 118 | t.Fatalf("%d %s: row %+v, registrations %d", refusal.status, refusal.body, row, n) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | r := newRig(t) |
| 123 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 124 | r.enqueue(KindAlert, TargetDevice, "c2", false) |
| 125 | r.carlos(200, "", `{"status":429,"apns_id":"x","reason":"TooManyRequests"}`) |
| 126 | r.must(r.d.G.Model(&OutboxRecord{}).Where("collapse_id = ?", "c2").Update("next_at", at.Add(time.Second)).Error) |
| 127 | r.drain() |
| 128 | for _, row := range r.rows() { |
| 129 | if row.State != StatePending || row.NextAt.Before(at.Add(Backoff(1))) { |
| 130 | t.Fatalf("Apple throttled the device but %s did not wait: %+v", row.CollapseID, row) |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | r = newRig(t) |
| 135 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 136 | r.carlos(200, "", `{"status":503,"apns_id":"x","reason":"ServiceUnavailable"}`) |
| 137 | r.drain() |
| 138 | if row := r.rows()[0]; row.State != StatePending || !row.NextAt.Equal(at.Add(AppleRetry)) || row.Attempts != 1 { |
| 139 | t.Fatalf("Apple 503 %+v", row) |
| 140 | } |
| 141 | |
| 142 | for _, body := range []string{`{"status":410,"apns_id":"x","reason":"ExpiredToken","timestamp":` + jsonInt(at.Add(time.Hour).UnixMilli()) + `}`, `{"status":400,"apns_id":"x","reason":"DeviceTokenNotForTopic"}`} { |
| 143 | r := newRig(t) |
| 144 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 145 | r.carlos(200, "", body) |
| 146 | r.drain() |
| 147 | var n int64 |
| 148 | r.d.G.Model(&Registration{}).Count(&n) |
| 149 | if n != 0 { |
| 150 | t.Fatalf("%s kept the registration", body) |
| 151 | } |
| 152 | } |
| 153 | // A 410 whose token Apple last knew before this registration: the |
| 154 | // registration is newer, and stays. |
| 155 | r = newRig(t) |
| 156 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 157 | r.carlos(200, "", `{"status":410,"apns_id":"x","reason":"Unregistered","timestamp":`+jsonInt(at.Add(-time.Hour).UnixMilli())+`}`) |
| 158 | r.drain() |
| 159 | var n int64 |
| 160 | r.d.G.Model(&Registration{}).Count(&n) |
| 161 | if n != 1 { |
| 162 | t.Fatal("a registration newer than Apple's 410 was deleted") |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | func jsonInt(n int64) string { b, _ := json.Marshal(n); return string(b) } |
| 167 | |
| 168 | // TestCarlosRequest: a message as the verb takes it (design §4.1): the |
| 169 | // field names, apns_id the row's UUID, expiration in Unix seconds, the |
| 170 | // payload a compact object, and nothing over the limits. |
| 171 | func TestCarlosRequest(t *testing.T) { |
| 172 | m := Message{ID: NewID(), Token: devToken, Environment: wire.APNsProduction, Topic: Topic, PushType: TypeAlert, Priority: 10, CollapseID: "c1", Expiration: at, Payload: []byte("{\n \"aps\": {\"badge\": 3}\n}")} |
| 173 | raw, err := CarlosRequestOf(m) |
| 174 | if err != nil { |
| 175 | t.Fatal(err) |
| 176 | } |
| 177 | var got map[string]any |
| 178 | if err := json.Unmarshal(raw, &got); err != nil { |
| 179 | t.Fatal(err) |
| 180 | } |
| 181 | want := map[string]any{"device_token": devToken, "topic": Topic, "push_type": "alert", "priority": float64(10), "collapse_id": "c1", "expiration": float64(at.Unix()), "apns_id": m.ID, "environment": "production", "payload": map[string]any{"aps": map[string]any{"badge": float64(3)}}} |
| 182 | if g, _ := json.Marshal(got); string(g) != func() string { w, _ := json.Marshal(want); return string(w) }() { |
| 183 | t.Fatalf("request %s", raw) |
| 184 | } |
| 185 | if !bytes.Contains(raw, []byte(`"payload":{"aps":{"badge":3}}`)) { |
| 186 | t.Fatalf("payload not compacted: %s", raw) |
| 187 | } |
| 188 | // The limit is on the payload as sent, compacted: spaces do not count. |
| 189 | fits := `{"aps":{"alert":{"body":"` + strings.Repeat("x", MaxPayload-40) + `"}}}` |
| 190 | m.Payload = []byte(strings.ReplaceAll(fits, ":", " : ")) |
| 191 | if raw, err := CarlosRequestOf(m); err != nil || !bytes.Contains(raw, []byte(fits)) { |
| 192 | t.Fatal("a payload that fits once compacted", err) |
| 193 | } |
| 194 | m.Payload = []byte(`{"aps":{"alert":{"body":"` + strings.Repeat("x", MaxPayload) + `"}}}`) |
| 195 | if _, err := CarlosRequestOf(m); !errors.Is(err, ErrTooLarge) { |
| 196 | t.Fatal("an oversized payload", err) |
| 197 | } |
| 198 | m.Payload = []byte(`["not an object"]`) |
| 199 | if _, err := CarlosRequestOf(m); err == nil { |
| 200 | t.Fatal("a payload that is not an object") |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // TestCarlosResult: the verb's answers read back: Apple's answer on a |
| 205 | // 200 (with a 410's timestamp in milliseconds), the platform's code and |
| 206 | // Retry-After otherwise, a 401's plain text without a code. |
| 207 | func TestCarlosResult(t *testing.T) { |
| 208 | r, err := CarlosResult(200, "", []byte(`{"status":410,"apns_id":"a1","reason":"Unregistered","timestamp":1763683200000}`)) |
| 209 | if err != nil || r.Status != 410 || r.APNsID != "a1" || !r.Timestamp.Equal(time.UnixMilli(1763683200000)) || !r.Apple() || !r.Gone() { |
| 210 | t.Fatalf("Apple's 410 %+v %v", r, err) |
| 211 | } |
| 212 | r, err = CarlosResult(429, "300", []byte(`{"code":"PAUSED"}`)) |
| 213 | if err != nil || r.Refused != 429 || r.Code != "PAUSED" || r.RetryAfter != 300*time.Second || r.Apple() { |
| 214 | t.Fatalf("PAUSED %+v %v", r, err) |
| 215 | } |
| 216 | if r, err = CarlosResult(401, "", []byte("unauthorized")); err != nil || r.Refused != 401 || r.Code != "" || r.Apple() { |
| 217 | t.Fatalf("401 %+v %v", r, err) |
| 218 | } |
| 219 | if _, err := CarlosResult(200, "", []byte("{}")); err == nil { |
| 220 | t.Fatal("a 200 without Apple's answer") |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | // TestSenderCheckOutcomes: only a device gone for good (revoked, its |
| 225 | // person removed) loses its registration; one not current now (expired) |
| 226 | // has the row dropped and stays registered; a failed lookup sends nothing |
| 227 | // and keeps the row for a later pass. |
| 228 | func TestSenderCheckOutcomes(t *testing.T) { |
| 229 | for name, c := range map[string]struct { |
| 230 | err error |
| 231 | state string |
| 232 | regs int64 |
| 233 | }{ |
| 234 | "gone": {ErrGone, StateDropped, 0}, |
| 235 | "expired": {ErrNotCurrent, StateDropped, 1}, |
| 236 | "lookup err": {errors.New("database is locked"), StatePending, 1}, |
| 237 | } { |
| 238 | r := newRig(t) |
| 239 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 240 | r.s.Check = func(*gorm.DB, string, string) error { return c.err } |
| 241 | r.drain() |
| 242 | var n int64 |
| 243 | r.d.G.Model(&Registration{}).Count(&n) |
| 244 | if row := r.rows()[0]; len(r.sent) != 0 || row.State != c.state || n != c.regs { |
| 245 | t.Fatalf("%s: sent %d, row %+v, registrations %d", name, len(r.sent), row, n) |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | // TestSenderExpiredAndOversized: a row past its expiration is dropped |
| 251 | // unsent; a payload over 4 KB is never sent. |
| 252 | func TestSenderExpiredAndOversized(t *testing.T) { |
| 253 | r := newRig(t) |
| 254 | r.enqueue(KindActivityUpdate, TargetDevice, "", false) |
| 255 | r.now = at.Add(time.Hour) |
| 256 | r.drain() |
| 257 | if row := r.rows()[0]; len(r.sent) != 0 || row.State != StateDropped || row.Reason != "expired" { |
| 258 | t.Fatalf("expired %+v", row) |
| 259 | } |
| 260 | r = newRig(t) |
| 261 | sealed, err := testBox.seal(domainPayload, `{"aps":{"alert":{"body":"`+strings.Repeat("x", MaxPayload)+`"}}}`) |
| 262 | r.must(err) |
| 263 | r.must(r.d.G.Create(&OutboxRecord{ID: NewID(), Person: "p@example.com", Credential: "cr1", Kind: KindAlert, Target: TargetDevice, PushType: TypeAlert, Priority: 10, Payload: sealed, State: StatePending, NextAt: at, CreatedAt: at, UpdatedAt: at}).Error) |
| 264 | r.drain() |
| 265 | if row := r.rows()[0]; len(r.sent) != 0 || row.State != StateFailed || row.Reason != "payload_too_large" { |
| 266 | t.Fatalf("oversized %+v", row) |
| 267 | } |
| 268 | big := Intent{Kind: KindActivityUpdate, TaskID: "tk1", State: &wire.LiveActivityState{TaskID: "tk1", Activity: strings.Repeat("y", MaxPayload)}} |
| 269 | if _, _, err := Render(big, copyStub, 0, at); !errors.Is(err, ErrTooLarge) { |
| 270 | t.Fatal("Render wrote an oversized payload", err) |
| 271 | } |
| 272 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| 273 | if err := Enqueue(tx, testBox, OutboxRecord{Credential: "cr1", Payload: strings.Repeat("z", MaxPayload+1)}, false); !errors.Is(err, ErrTooLarge) { |
| 274 | t.Error("Enqueue kept an oversized payload", err) |
| 275 | } |
| 276 | return nil |
| 277 | })) |
| 278 | } |
| 279 | |
| 280 | // TestSenderTimeoutAndScrub: a send has the sender's deadline, and a |
| 281 | // transport's error or answer never brings the token into a log or row. |
| 282 | func TestSenderTimeoutAndScrub(t *testing.T) { |
| 283 | r := newRig(t) |
| 284 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 285 | r.s.Timeout = 50 * time.Millisecond |
| 286 | var logged []string |
| 287 | r.s.Errorf = func(msg string, args ...any) { |
| 288 | for _, a := range args { |
| 289 | if e, ok := a.(error); ok { |
| 290 | logged = append(logged, e.Error()) |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | r.s.Transport = transportFunc(func(ctx context.Context, m Message) (Result, error) { |
| 295 | deadline, ok := ctx.Deadline() |
| 296 | if !ok || time.Until(deadline) > 50*time.Millisecond { |
| 297 | t.Error("no send deadline") |
| 298 | } |
| 299 | <-ctx.Done() |
| 300 | return Result{Reason: "dial " + strings.ToUpper(m.Token)}, errors.New("POST https://api.push.apple.com/3/device/" + m.Token + ": " + ctx.Err().Error()) |
| 301 | }) |
| 302 | r.drain() |
| 303 | row := r.rows()[0] |
| 304 | if row.State != StatePending || row.Attempts != 1 || len(logged) != 1 { |
| 305 | t.Fatalf("row %+v, logged %v", row, logged) |
| 306 | } |
| 307 | if strings.Contains(strings.ToLower(logged[0]+row.Reason), devToken) || !strings.Contains(logged[0], "deadline exceeded") { |
| 308 | t.Fatalf("token reached the log or row: %q %q", logged[0], row.Reason) |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | // TestTokensNeverSQLText: registering, keeping an activity token, |
| 313 | // writing a push and sending it never puts a token or a payload's text |
| 314 | // into a statement, as the database's slow and failed query log would |
| 315 | // print it; at rest they are sealed. |
| 316 | func TestTokensNeverSQLText(t *testing.T) { |
| 317 | r := newRig(t) |
| 318 | var sql bytes.Buffer |
| 319 | logged := r.d.G.Session(&gorm.Session{Logger: logger.New(log.New(&sql, "", 0), logger.Config{LogLevel: logger.Info})}) |
| 320 | r.s.Write = func(ctx context.Context, fn func(*gorm.DB) error) error { |
| 321 | return logged.WithContext(ctx).Transaction(fn) |
| 322 | } |
| 323 | const text = "Merge the login fix on main?" |
| 324 | r.must(logged.Transaction(func(tx *gorm.DB) error { |
| 325 | if _, err := Register(tx, testBox, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, StartToken: startToken}, at); err != nil { |
| 326 | return err |
| 327 | } |
| 328 | if err := RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at); err != nil { |
| 329 | return err |
| 330 | } |
| 331 | return Enqueue(tx, testBox, OutboxRecord{Person: "p@example.com", Credential: "cr1", Kind: KindAlert, Target: TargetDevice, PushType: TypeAlert, Priority: 10, Payload: `{"aps":{"alert":{"body":"` + text + `"}}}`, NextAt: at, CreatedAt: at, UpdatedAt: at}, false) |
| 332 | })) |
| 333 | if r.drain() != 1 || string(r.sent[0].Payload) != `{"aps":{"alert":{"body":"`+text+`"}}}` || r.sent[0].Token != devToken { |
| 334 | t.Fatalf("sent %+v", r.sent) |
| 335 | } |
| 336 | for _, secret := range []string{devToken, startToken, actToken, text} { |
| 337 | if strings.Contains(sql.String(), secret) { |
| 338 | t.Fatalf("%q is SQL text", secret) |
| 339 | } |
| 340 | } |
| 341 | if !strings.Contains(sql.String(), "push_outbox") { |
| 342 | t.Fatal("the statements were not captured") |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | // TestRegisterTakesTokens: a token another credential holds (the phone |
| 347 | // signed out offline and paired again) leaves that credential: its |
| 348 | // registration, what waits for it, and its activity tokens holding it. |
| 349 | func TestRegisterTakesTokens(t *testing.T) { |
| 350 | r := newRig(t) |
| 351 | // A token that will not open (sealed under another key) stops nothing. |
| 352 | r.must(r.d.G.Create(&Registration{Credential: "cr_old", Person: "o@example.com", Token: "not sealed here", CreatedAt: at, UpdatedAt: at}).Error) |
| 353 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| 354 | return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at) |
| 355 | })) |
| 356 | r.enqueue(KindAlert, TargetDevice, "c1", false) |
| 357 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| 358 | _, err := Register(tx, testBox, "q@example.com", "cr2", wire.RegisterPush{Token: startToken, Environment: wire.APNsProduction, Platform: wire.PlatformIOS}, at) |
| 359 | return err |
| 360 | })) |
| 361 | var regs []Registration |
| 362 | r.must(r.d.G.Find(®s).Error) |
| 363 | if len(regs) != 2 || regs[0].Credential != "cr2" && regs[1].Credential != "cr2" || r.rows()[0].State != StateDropped { |
| 364 | t.Fatalf("cr1 kept the token: %+v", regs) |
| 365 | } |
| 366 | for _, reg := range regs { |
| 367 | if reg.Credential == "cr1" { |
| 368 | t.Fatal("cr1 kept the token") |
| 369 | } |
| 370 | } |
| 371 | // cr1 registers again with its own token and keeps an activity's; |
| 372 | // that activity token, registered by cr2, leaves cr1 alone. |
| 373 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| 374 | if _, err := Register(tx, testBox, "p@example.com", "cr1", wire.RegisterPush{Token: devToken, Environment: wire.APNsProduction, Platform: wire.PlatformIOS}, at); err != nil { |
| 375 | return err |
| 376 | } |
| 377 | return RegisterActivity(tx, testBox, "p@example.com", "cr1", "tk1", actToken, at) |
| 378 | })) |
| 379 | r.must(r.d.G.Transaction(func(tx *gorm.DB) error { |
| 380 | return RegisterActivity(tx, testBox, "q@example.com", "cr2", "tk2", actToken, at) |
| 381 | })) |
| 382 | var acts []ActivityToken |
| 383 | r.must(r.d.G.Find(&acts).Error) |
| 384 | r.must(r.d.G.Find(®s).Error) |
| 385 | if len(acts) != 1 || acts[0].Credential != "cr2" || len(regs) != 3 { |
| 386 | t.Fatalf("activity tokens %+v, registrations %d", acts, len(regs)) |
| 387 | } |
| 388 | } |
| 389 | |