| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/base64" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 13 | "amadan.net/oficina/equipo/internal/equipo/push" |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "gorm.io/gorm" |
| 16 | ) |
| 17 | |
| 18 | const ( |
| 19 | pushDevice = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11" |
| 20 | pushStart = "bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22" |
| 21 | pushMac = "dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44dd44" |
| 22 | ) |
| 23 | |
| 24 | // pushRig is a housekeeping rig with the outbox on, owner's iPhone |
| 25 | // registered (credential cr_phone) and devices current until revoked. |
| 26 | type pushRig struct { |
| 27 | *hkRig |
| 28 | revoked map[string]bool |
| 29 | audits []string |
| 30 | } |
| 31 | |
| 32 | func newPushRig(t *testing.T) *pushRig { |
| 33 | t.Helper() |
| 34 | r := &pushRig{hkRig: newHKRig(t), revoked: map[string]bool{}} |
| 35 | r.s.authority.Origin = "https://oficina.equipo.example" |
| 36 | r.s.authority.PushDevice = func(_ *gorm.DB, person, credential string) error { |
| 37 | if r.revoked[credential] || !strings.HasPrefix(credential, "cr_") { |
| 38 | return ErrForbidden |
| 39 | } |
| 40 | return nil |
| 41 | } |
| 42 | r.s.authority.Audit = func(_ *gorm.DB, actor, kind, record string) error { |
| 43 | r.audits = append(r.audits, actor+" "+kind+" "+record) |
| 44 | return nil |
| 45 | } |
| 46 | // Sealing as the instance key does, for the tests: what it seals never |
| 47 | // shows the token or the text. |
| 48 | r.s.authority.Seal = func(domain string, v any) (string, error) { |
| 49 | b, err := json.Marshal(v) |
| 50 | return domain + ":" + base64.StdEncoding.EncodeToString(b), err |
| 51 | } |
| 52 | r.s.authority.Open = func(domain, sealed string, v any) error { |
| 53 | raw, ok := strings.CutPrefix(sealed, domain+":") |
| 54 | if !ok { |
| 55 | return errors.New("sealed for another domain") |
| 56 | } |
| 57 | b, err := base64.StdEncoding.DecodeString(raw) |
| 58 | if err != nil { |
| 59 | return err |
| 60 | } |
| 61 | return json.Unmarshal(b, v) |
| 62 | } |
| 63 | r.s.SetPush(true) |
| 64 | r.register(hkOwner, "cr_phone", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, StartToken: pushStart}) |
| 65 | r.clear() |
| 66 | return r |
| 67 | } |
| 68 | |
| 69 | // clear forgets the rows written so far (a registration's badge). |
| 70 | func (r *pushRig) clear() { |
| 71 | r.t.Helper() |
| 72 | r.must(r.s.db.G.Where("1 = 1").Delete(&push.OutboxRecord{}).Error) |
| 73 | } |
| 74 | |
| 75 | func (r *pushRig) register(person, credential string, in wire.RegisterPush) { |
| 76 | r.t.Helper() |
| 77 | if _, err := r.s.RegisterPush(r.ctx, person, credential, in); err != nil { |
| 78 | r.t.Fatal(err) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // outbox is the rows written, oldest first, their payloads opened. |
| 83 | func (r *pushRig) outbox() []push.OutboxRecord { |
| 84 | r.t.Helper() |
| 85 | var out []push.OutboxRecord |
| 86 | r.must(r.s.db.G.Order("created_at, kind, collapse_id").Find(&out).Error) |
| 87 | for i := range out { |
| 88 | p, err := r.s.pushBox().OpenPayload(out[i].Payload) |
| 89 | r.must(err) |
| 90 | out[i].Payload = p |
| 91 | } |
| 92 | return out |
| 93 | } |
| 94 | |
| 95 | // activity sends the running activity's own token for the task, as the |
| 96 | // app does once the activity started. |
| 97 | func (r *pushRig) activity(credential, task string) error { |
| 98 | return r.s.RegisterActivity(r.ctx, hkOwner, credential, wire.RegisterActivity{TaskID: task, Token: pushStart}) |
| 99 | } |
| 100 | |
| 101 | func kinds(rows []push.OutboxRecord) string { |
| 102 | var out []string |
| 103 | for _, row := range rows { |
| 104 | out = append(out, row.Kind) |
| 105 | } |
| 106 | return strings.Join(out, " ") |
| 107 | } |
| 108 | |
| 109 | // step saves the task with a step of its in the state given. |
| 110 | func (r *pushRig) step(k *taskRecord, id, specialist, state string) { |
| 111 | r.t.Helper() |
| 112 | r.must(r.tx(func(t *txn) error { |
| 113 | s := stepRecord{ID: id, TaskID: k.ID, Idx: 1, Specialist: specialist, Person: k.Creator, State: state, Attempt: 1, Terminated: state == wire.StepFailed, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| 114 | if err := t.db.Save(&s).Error; err != nil { |
| 115 | return err |
| 116 | } |
| 117 | return t.saveTask(k) |
| 118 | })) |
| 119 | r.now = r.now.Add(time.Second) |
| 120 | } |
| 121 | |
| 122 | func (r *pushRig) stage(k *taskRecord, stage string) { |
| 123 | r.t.Helper() |
| 124 | k.Stage = stage |
| 125 | r.must(r.tx(func(t *txn) error { return t.saveTask(k) })) |
| 126 | r.now = r.now.Add(time.Second) |
| 127 | } |
| 128 | |
| 129 | // TestPushOutboxInEngineTransaction: the rows are written by the change's |
| 130 | // own transaction, beside its event, and vanish with it when it rolls |
| 131 | // back; with the outbox off nothing is written. |
| 132 | func TestPushOutboxInEngineTransaction(t *testing.T) { |
| 133 | r := newPushRig(t) |
| 134 | k := r.task("tk1", "Fix login", hkOwner) |
| 135 | events := r.count("SELECT count(*) FROM chat_events") |
| 136 | boom := errors.New("boom") |
| 137 | err := r.tx(func(t *txn) error { |
| 138 | s := stepRecord{ID: "s1", TaskID: k.ID, Idx: 1, Specialist: wire.SpecialistEngineering, Person: hkOwner, State: wire.StepRunning, Attempt: 1, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| 139 | if err := t.db.Create(&s).Error; err != nil { |
| 140 | return err |
| 141 | } |
| 142 | if err := t.saveTask(&k); err != nil { |
| 143 | return err |
| 144 | } |
| 145 | var n int64 |
| 146 | if err := t.db.Model(&push.OutboxRecord{}).Count(&n).Error; err != nil || n != 1 { |
| 147 | r.t.Errorf("inside the transaction: %d rows, %v", n, err) |
| 148 | } |
| 149 | return boom |
| 150 | }) |
| 151 | if !errors.Is(err, boom) || len(r.outbox()) != 0 || r.count("SELECT count(*) FROM chat_events") != events || r.count("SELECT count(*) FROM push_tasks") != 0 { |
| 152 | t.Fatal("a rolled back change left its push behind") |
| 153 | } |
| 154 | k = r.load("tk1") |
| 155 | r.s.SetPush(false) |
| 156 | r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| 157 | if len(r.outbox()) != 0 { |
| 158 | t.Fatal("the outbox was written while off") |
| 159 | } |
| 160 | r.s.SetPush(true) |
| 161 | r.stage(&k, wire.StageInProgress) |
| 162 | if got := kinds(r.outbox()); got != push.KindActivityStart { |
| 163 | t.Fatalf("outbox %q", got) |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | // TestPushTaskLifecycle drives a task through the engine: dispatch starts |
| 168 | // its Live Activity by push-to-start, a stage change updates it, needing |
| 169 | // the person updates it urgently with the badge (their Needs you count), |
| 170 | // and its end alerts passively and ends the activity. |
| 171 | func TestPushTaskLifecycle(t *testing.T) { |
| 172 | r := newPushRig(t) |
| 173 | k := r.task("tk1", "Fix login", hkOwner) |
| 174 | r.stage(&k, wire.StageNoted) |
| 175 | if len(r.outbox()) != 0 { |
| 176 | t.Fatal("a noted task pushed") |
| 177 | } |
| 178 | r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| 179 | rows := r.outbox() |
| 180 | if kinds(rows) != push.KindActivityStart || rows[0].Target != push.TargetStart || rows[0].Priority != 10 || rows[0].PushType != push.TypeLiveActivity { |
| 181 | t.Fatalf("start %+v", rows) |
| 182 | } |
| 183 | var p struct { |
| 184 | APS struct { |
| 185 | ContentState wire.LiveActivityState `json:"content-state"` |
| 186 | Attributes wire.LiveActivityAttributes `json:"attributes"` |
| 187 | } `json:"aps"` |
| 188 | } |
| 189 | r.must(json.Unmarshal([]byte(rows[0].Payload), &p)) |
| 190 | if s := p.APS.ContentState; s.TaskID != "tk1" || s.Specialist != wire.SpecialistEngineering || s.Activity != "work.activity.working" || s.Tone != wire.TonePositive { |
| 191 | t.Fatalf("content state %+v", s) |
| 192 | } |
| 193 | // The activity names its team, so a device never sends its token to |
| 194 | // another team's instance, even after a relaunch. |
| 195 | if a := p.APS.Attributes; a.TaskID != "tk1" || a.Origin != r.s.authority.Origin || a.Origin == "" { |
| 196 | t.Fatalf("attributes %+v", a) |
| 197 | } |
| 198 | // The activity's own token arrives: it hears the whole state at once. |
| 199 | r.must(r.activity("cr_phone", "tk1")) |
| 200 | if rows = r.outbox(); kinds(rows[1:]) != push.KindActivityUpdate || rows[1].Priority != 10 || rows[1].Target != push.TargetActivity { |
| 201 | t.Fatalf("catch-up %+v", rows[1:]) |
| 202 | } |
| 203 | r.stage(&k, wire.StageInReview) |
| 204 | if rows = r.outbox(); kinds(rows[2:]) != push.KindActivityUpdate || rows[2].Priority != 5 || rows[2].Target != push.TargetActivity { |
| 205 | t.Fatalf("update %+v", rows[2:]) |
| 206 | } |
| 207 | r.step(&k, "s1", wire.SpecialistEngineering, wire.StepDone) |
| 208 | r.stage(&k, wire.StageReadyToMerge) |
| 209 | rows = r.outbox() |
| 210 | last := rows[len(rows)-2:] |
| 211 | // Urgent and silent: a card, if any, is the one sound. |
| 212 | if kinds(last) != "activity_update badge" || last[0].Priority != 10 || strings.Contains(last[0].Payload, `"alert"`) || last[1].Payload != `{"aps":{"badge":1}}` { |
| 213 | t.Fatalf("needs you %+v", last) |
| 214 | } |
| 215 | r.stage(&k, wire.StageDone) |
| 216 | rows = r.outbox() |
| 217 | last = rows[len(rows)-2:] |
| 218 | // The unsent badge took the new count (it coalesces). |
| 219 | if kinds(last) != "activity_end passive" || last[1].CollapseID != "task:tk1" || rows[len(rows)-3].Payload != `{"aps":{"badge":0}}` { |
| 220 | t.Fatalf("end %s", kinds(rows)) |
| 221 | } |
| 222 | // Seen again ended: nothing more. |
| 223 | n := len(rows) |
| 224 | r.stage(&k, wire.StageDone) |
| 225 | if len(r.outbox()) != n { |
| 226 | t.Fatal("an ended task pushed again") |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | // TestPushAtMostThreeActivities: a fourth dispatched task ends the oldest |
| 231 | // started one's Live Activity. |
| 232 | func TestPushAtMostThreeActivities(t *testing.T) { |
| 233 | r := newPushRig(t) |
| 234 | for _, id := range []string{"tk1", "tk2", "tk3", "tk4"} { |
| 235 | k := r.task(id, "Task "+id, hkOwner) |
| 236 | r.step(&k, "s"+id, wire.SpecialistEngineering, wire.StepRunning) |
| 237 | } |
| 238 | var ends []push.OutboxRecord |
| 239 | for _, row := range r.outbox() { |
| 240 | if row.Kind == push.KindActivityEnd { |
| 241 | ends = append(ends, row) |
| 242 | } |
| 243 | } |
| 244 | if len(ends) != 1 || ends[0].TaskID != "tk1" || !strings.Contains(ends[0].Payload, `"outcome":"replaced"`) { |
| 245 | t.Fatalf("ends %+v", ends) |
| 246 | } |
| 247 | live, err := push.LiveTasks(r.s.db.G, hkOwner) |
| 248 | if err != nil || len(live) != wire.MaxLiveActivities || live[0].TaskID != "tk2" { |
| 249 | t.Fatalf("live %+v %v", live, err) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // TestPushActivityLineOnceAMinute: activity lines update a running |
| 254 | // activity at most once a minute. |
| 255 | func TestPushActivityLineOnceAMinute(t *testing.T) { |
| 256 | r := newPushRig(t) |
| 257 | k := r.task("tk1", "Fix login", hkOwner) |
| 258 | r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| 259 | s := stepRecord{ID: "s1", TaskID: "tk1", Person: hkOwner} |
| 260 | line := func(subject string) { |
| 261 | r.must(r.tx(func(t *txn) error { |
| 262 | return t.pushLine(s, wire.ActivityLine{Kind: wire.ActivityRead, Subject: subject, At: r.now}) |
| 263 | })) |
| 264 | } |
| 265 | // No token yet: the line goes nowhere, and is not remembered as told. |
| 266 | line("README.md") |
| 267 | if kinds(r.outbox()) != push.KindActivityStart { |
| 268 | t.Fatalf("a line with no activity token %s", kinds(r.outbox())) |
| 269 | } |
| 270 | r.must(r.activity("cr_phone", "tk1")) |
| 271 | line("README.md") |
| 272 | r.now = r.now.Add(20 * time.Second) |
| 273 | line("main.go") |
| 274 | r.now = r.now.Add(time.Minute) |
| 275 | line("go.mod") |
| 276 | rows := r.outbox() |
| 277 | if kinds(rows) != "activity_start activity_update activity_update activity_update" || !strings.Contains(rows[2].Payload, "work.activity.read") || !strings.Contains(rows[3].Payload, "go.mod") { |
| 278 | t.Fatalf("lines %s", kinds(rows)) |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | func (r *pushRig) card(id, state string) cardRecord { return r.cardFor(hkOwner, id, state) } |
| 283 | |
| 284 | func (r *pushRig) cardFor(person, id, state string) cardRecord { |
| 285 | r.t.Helper() |
| 286 | c := cardRecord{ID: id, Person: person, Kind: wire.CardQuestion, State: state, Question: "Which branch should the fix go on?", Options: `["main","release"]`, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| 287 | r.must(r.tx(func(t *txn) error { |
| 288 | if err := t.db.Create(&c).Error; err != nil { |
| 289 | return err |
| 290 | } |
| 291 | return t.cardEvent(c) |
| 292 | })) |
| 293 | return c |
| 294 | } |
| 295 | |
| 296 | // TestPushCardOpensOnce: an open card alerts its person once, with its |
| 297 | // question; written again, or set aside, it does not alert again, and |
| 298 | // set aside it keeps its place in Needs you. |
| 299 | func TestPushCardOpensOnce(t *testing.T) { |
| 300 | r := newPushRig(t) |
| 301 | c := r.card("c1", wire.CardOpen) |
| 302 | rows := r.outbox() |
| 303 | if kinds(rows) != push.KindAlert || rows[0].CollapseID != "c1" || rows[0].Priority != 10 || !strings.Contains(rows[0].Payload, "Which branch should the fix go on?") { |
| 304 | t.Fatalf("card alert %+v", rows) |
| 305 | } |
| 306 | r.must(r.tx(func(t *txn) error { return t.cardEvent(c) })) |
| 307 | out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: true, Revision: 1}) |
| 308 | if err != nil || !out.Aside || out.State != wire.CardOpen { |
| 309 | t.Fatalf("set aside %+v %v", out, err) |
| 310 | } |
| 311 | if len(r.outbox()) != 1 { |
| 312 | t.Fatal("the card alerted again") |
| 313 | } |
| 314 | r.card("c2", wire.CardAnswered) |
| 315 | if len(r.outbox()) != 1 { |
| 316 | t.Fatal("an answered card alerted") |
| 317 | } |
| 318 | // The mark outlives the outbox: pruned rows do not make it alert again. |
| 319 | r.must(r.s.db.G.Where("1 = 1").Delete(&push.OutboxRecord{}).Error) |
| 320 | r.must(r.tx(func(t *txn) error { return t.cardEvent(c) })) |
| 321 | if len(r.outbox()) != 0 { |
| 322 | t.Fatal("the card alerted again once its row was pruned") |
| 323 | } |
| 324 | // A card that opened before the person had a device never alerts. |
| 325 | r.cardFor(hkMember, "c3", wire.CardOpen) |
| 326 | r.register(hkMember, "cr_member", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS}) |
| 327 | r.must(r.tx(func(t *txn) error { |
| 328 | var c cardRecord |
| 329 | if err := t.db.Where("id = ?", "c3").Take(&c).Error; err != nil { |
| 330 | return err |
| 331 | } |
| 332 | return t.cardEvent(c) |
| 333 | })) |
| 334 | for _, row := range r.outbox() { |
| 335 | if row.Kind == push.KindAlert { |
| 336 | t.Fatal("a card older than the device alerted", row.CollapseID) |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | // TestPushNeverToRemovedOrRevoked: a person off the roster, or a device |
| 342 | // revoked, gets no row at all. |
| 343 | func TestPushNeverToRemovedOrRevoked(t *testing.T) { |
| 344 | r := newPushRig(t) |
| 345 | r.register(hkOwner, "cr_mac", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS}) |
| 346 | r.clear() |
| 347 | r.revoked["cr_mac"] = true |
| 348 | r.card("c1", wire.CardOpen) |
| 349 | rows := r.outbox() |
| 350 | if len(rows) != 1 || rows[0].Credential != "cr_phone" { |
| 351 | t.Fatalf("revoked device pushed: %+v", rows) |
| 352 | } |
| 353 | r.must(r.tx(func(t *txn) error { return t.db.Exec("UPDATE members SET active = 0 WHERE address = ?", hkOwner).Error })) |
| 354 | r.card("c2", wire.CardOpen) |
| 355 | if len(r.outbox()) != 1 { |
| 356 | t.Fatal("a removed person was pushed") |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | // TestPushReplyOnlyWhenNotFollowing: a finished reply alerts with its |
| 361 | // first line, unless the person has the stream open. |
| 362 | func TestPushReplyOnlyWhenNotFollowing(t *testing.T) { |
| 363 | r := newPushRig(t) |
| 364 | reply := func(id string) { |
| 365 | r.must(r.tx(func(t *txn) error { |
| 366 | turn := turnRecord{ID: id, Person: hkOwner, State: wire.TurnRunning, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| 367 | m := messageRecord{ID: "m_" + id, Person: hkOwner, IdempotencyKey: "reply:" + id, Role: wire.RoleCoordinator, Text: "**Done.** The fix is on its branch.\nDetails follow.", TurnID: id, Revision: 1, CreatedAt: r.now} |
| 368 | if err := t.db.Create(&turn).Error; err != nil { |
| 369 | return err |
| 370 | } |
| 371 | if err := t.db.Create(&m).Error; err != nil { |
| 372 | return err |
| 373 | } |
| 374 | turn.State, turn.ReplyID = wire.TurnReplied, m.ID |
| 375 | return t.saveTurn(&turn) |
| 376 | })) |
| 377 | } |
| 378 | done := r.s.Hub().Follow(hkOwner) |
| 379 | reply("t_watched") |
| 380 | if len(r.outbox()) != 0 { |
| 381 | t.Fatal("pushed a reply the person was watching") |
| 382 | } |
| 383 | done() |
| 384 | reply("t_away") |
| 385 | rows := r.outbox() |
| 386 | if len(rows) != 1 || rows[0].CollapseID != "reply:t_away" || !strings.Contains(rows[0].Payload, `"body":"Done. The fix is on its branch."`) { |
| 387 | t.Fatalf("reply %+v", rows) |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | // TestRegisterPushAuthority: only a device credential of a current |
| 392 | // person registers; the audit names the credential, never a token; an |
| 393 | // activity token is only for a task of the person's that has not ended. |
| 394 | func TestRegisterPushAuthority(t *testing.T) { |
| 395 | r := newPushRig(t) |
| 396 | in := wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS} |
| 397 | // A browser session has no device credential: refused even where the |
| 398 | // device check would pass. |
| 399 | check := r.s.authority.PushDevice |
| 400 | r.s.authority.PushDevice = func(*gorm.DB, string, string) error { return nil } |
| 401 | if _, err := r.s.RegisterPush(r.ctx, hkOwner, "", in); !errors.Is(err, ErrForbidden) { |
| 402 | t.Fatal("a browser session registered", err) |
| 403 | } |
| 404 | r.s.authority.PushDevice = check |
| 405 | r.revoked["cr_phone"] = true |
| 406 | if _, err := r.s.RegisterPush(r.ctx, hkOwner, "cr_phone", in); !errors.Is(err, ErrForbidden) { |
| 407 | t.Fatal("a revoked device registered", err) |
| 408 | } |
| 409 | r.revoked["cr_phone"] = false |
| 410 | if _, err := r.s.RegisterPush(r.ctx, hkOwner, "cr_phone", wire.RegisterPush{Token: "nothex", Environment: wire.APNsProduction, Platform: wire.PlatformIOS}); !errors.Is(err, ErrInvalid) { |
| 411 | t.Fatal("a bad token registered", err) |
| 412 | } |
| 413 | for _, a := range r.audits { |
| 414 | if strings.Contains(a, pushDevice) || strings.Contains(a, pushStart) { |
| 415 | t.Fatal("token in audit", a) |
| 416 | } |
| 417 | } |
| 418 | if len(r.audits) != 1 || r.audits[0] != hkOwner+" push.register cr_phone" { |
| 419 | t.Fatalf("audits %v", r.audits) |
| 420 | } |
| 421 | r.task("tk_mine", "Mine", hkOwner) |
| 422 | r.task("tk_theirs", "Theirs", hkMember) |
| 423 | act := func(task string) error { |
| 424 | return r.s.RegisterActivity(r.ctx, hkOwner, "cr_phone", wire.RegisterActivity{TaskID: task, Token: pushStart}) |
| 425 | } |
| 426 | if err := act("tk_theirs"); !errors.Is(err, ErrNotFound) { |
| 427 | t.Fatal("another's task", err) |
| 428 | } |
| 429 | if err := act("tk_mine"); err != nil { |
| 430 | t.Fatal(err) |
| 431 | } |
| 432 | k := r.load("tk_mine") |
| 433 | r.stage(&k, wire.StageCancelled) |
| 434 | // Its end waits for the device: the token is still taken. |
| 435 | if err := act("tk_mine"); err != nil { |
| 436 | t.Fatal("an ended task whose end waits", err) |
| 437 | } |
| 438 | r.must(r.s.db.G.Model(&push.OutboxRecord{}).Where("1 = 1").Update("state", push.StateSent).Error) |
| 439 | if err := act("tk_mine"); !errors.Is(err, ErrTaskEnded) { |
| 440 | t.Fatal("an ended task with nothing waiting", err) |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | // TestPushRegistrationAnswersNoToken: the registration answers its |
| 445 | // environment and platform, never a token. |
| 446 | func TestPushRegistrationAnswersNoToken(t *testing.T) { |
| 447 | r := newPushRig(t) |
| 448 | h := &HTTP{Store: r.s} |
| 449 | out, err := h.Store.RegisterPush(personapi.WithVerifiedPrincipal(context.Background(), personapi.PersonPrincipal{Address: hkOwner, CredentialID: "cr_phone"}), hkOwner, "cr_phone", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsDevelopment, Platform: wire.PlatformIOS, StartToken: pushStart}) |
| 450 | raw, _ := json.Marshal(out) |
| 451 | if err != nil || !out.LiveActivities || strings.Contains(string(raw), pushDevice) || strings.Contains(string(raw), pushStart) { |
| 452 | t.Fatalf("registration %s %v", raw, err) |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | // TestSetAsideKeepsNeedsYou (D5): a card set aside still waits on its |
| 457 | // person, so its task stays in Needs you and the badge does not move; a |
| 458 | // stale revision or a card that no longer waits is a conflict carrying |
| 459 | // the card as it is. |
| 460 | func TestSetAsideKeepsNeedsYou(t *testing.T) { |
| 461 | r := newPushRig(t) |
| 462 | k := r.task("tk1", "Fix login", hkOwner) |
| 463 | r.stage(&k, wire.StageReadyToMerge) |
| 464 | c := cardRecord{ID: "c1", Person: hkOwner, Kind: wire.CardQuestion, State: wire.CardOpen, TaskID: "tk1", Question: "Merge it?", Options: `["yes","no"]`, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| 465 | r.must(r.s.db.G.Create(&c).Error) |
| 466 | before := len(r.outbox()) |
| 467 | // c1 opened with no alert decided (as one opened before push): setting |
| 468 | // it aside runs no push rule, so it does not alert now. |
| 469 | out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: true, Revision: 1}) |
| 470 | if err != nil || !out.Aside || out.Revision != 1 { |
| 471 | t.Fatalf("aside %+v %v", out, err) |
| 472 | } |
| 473 | list, err := r.s.NeedsYou(r.ctx, hkOwner) |
| 474 | if err != nil || len(list.Items) != 1 || list.Items[0].ID != "tk1" { |
| 475 | t.Fatalf("needs you %+v %v", list.Items, err) |
| 476 | } |
| 477 | for _, row := range r.outbox()[before:] { |
| 478 | if row.Kind == push.KindBadge { |
| 479 | t.Fatal("setting aside moved the badge") |
| 480 | } |
| 481 | if row.Kind == push.KindAlert { |
| 482 | t.Fatal("setting aside alerted", row.CollapseID) |
| 483 | } |
| 484 | } |
| 485 | if out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: false, Revision: 7}); !errors.Is(err, ErrCardConflict) || out.ID != "c1" || !out.Aside { |
| 486 | t.Fatalf("stale %+v %v", out, err) |
| 487 | } |
| 488 | r.must(r.s.db.G.Model(&cardRecord{}).Where("id = ?", "c1").Update("state", wire.CardAnswered).Error) |
| 489 | if out, err := r.s.SetCardVisibility(r.ctx, hkOwner, "c1", wire.SetCardVisibility{Aside: false, Revision: 1}); !errors.Is(err, ErrCardConflict) || out.State != wire.CardAnswered { |
| 490 | t.Fatalf("answered %+v %v", out, err) |
| 491 | } |
| 492 | if _, err := r.s.SetCardVisibility(r.ctx, hkMember, "c1", wire.SetCardVisibility{Aside: true, Revision: 1}); !errors.Is(err, ErrNotFound) { |
| 493 | t.Fatal("another person's card", err) |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | // TestPushTokenMovesToNewCredential: A signs out offline and B pairs on |
| 498 | // the same phone. Its token is B's alone: A's card questions never reach |
| 499 | // B's lock screen, and A's queued pushes go nowhere. |
| 500 | func TestPushTokenMovesToNewCredential(t *testing.T) { |
| 501 | r := newPushRig(t) |
| 502 | r.card("c_before", wire.CardOpen) |
| 503 | r.register(hkMember, "cr_b", wire.RegisterPush{Token: pushDevice, Environment: wire.APNsProduction, Platform: wire.PlatformIOS, StartToken: pushStart}) |
| 504 | r.card("c_a", wire.CardOpen) |
| 505 | r.cardFor(hkMember, "c_b", wire.CardOpen) |
| 506 | for _, row := range r.outbox() { |
| 507 | switch { |
| 508 | case row.Credential == "cr_phone" && row.State == push.StatePending: |
| 509 | t.Fatalf("A's push still waits for the phone: %+v", row) |
| 510 | case row.Person == hkOwner && row.Credential == "cr_b": |
| 511 | t.Fatalf("A's push went to B: %+v", row) |
| 512 | } |
| 513 | } |
| 514 | var regs []push.Registration |
| 515 | r.must(r.s.db.G.Find(®s).Error) |
| 516 | if len(regs) != 1 || regs[0].Credential != "cr_b" || regs[0].Person != hkMember { |
| 517 | t.Fatalf("registrations %+v", regs) |
| 518 | } |
| 519 | got := map[string]bool{} |
| 520 | for _, row := range r.outbox() { |
| 521 | got[row.Credential+" "+row.CollapseID] = true |
| 522 | } |
| 523 | if !got["cr_b c_b"] { |
| 524 | t.Fatalf("B's card did not alert B: %v", got) |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | // TestPushActivityTokenAfterEnd: a short task cancelled before its |
| 529 | // activity's token arrived still ends its activity: the token is taken |
| 530 | // while the end waits, and the end goes at once. An update with no token |
| 531 | // is never written, and the activity hears the whole state when its token |
| 532 | // arrives. |
| 533 | func TestPushActivityTokenAfterEnd(t *testing.T) { |
| 534 | r := newPushRig(t) |
| 535 | k := r.task("tk1", "Fix login", hkOwner) |
| 536 | r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| 537 | r.stage(&k, wire.StageInReview) |
| 538 | if kinds(r.outbox()) != push.KindActivityStart { |
| 539 | t.Fatalf("an update with no token was written: %s", kinds(r.outbox())) |
| 540 | } |
| 541 | r.stage(&k, wire.StageCancelled) |
| 542 | var end push.OutboxRecord |
| 543 | r.must(r.s.db.G.Where("kind = ?", push.KindActivityEnd).Take(&end).Error) |
| 544 | r.must(r.s.db.G.Model(&end).Updates(map[string]any{"attempts": 3, "next_at": r.now.Add(time.Hour)}).Error) |
| 545 | if err := r.activity("cr_phone", "tk1"); err != nil { |
| 546 | t.Fatal("the end waits, yet the token was refused:", err) |
| 547 | } |
| 548 | r.must(r.s.db.G.Where("id = ?", end.ID).Take(&end).Error) |
| 549 | if end.State != push.StatePending || end.NextAt.After(r.now) { |
| 550 | t.Fatalf("the end did not go at once: %+v", end) |
| 551 | } |
| 552 | if has, err := push.HasActivity(r.s.db.G, "cr_phone", "tk1"); err != nil || !has { |
| 553 | t.Fatal("token not kept", err) |
| 554 | } |
| 555 | |
| 556 | k2 := r.task("tk2", "Add search", hkOwner) |
| 557 | r.step(&k2, "s2", wire.SpecialistEngineering, wire.StepRunning) |
| 558 | r.stage(&k2, wire.StageInReview) |
| 559 | n := len(r.outbox()) |
| 560 | r.must(r.activity("cr_phone", "tk2")) |
| 561 | rows := r.outbox()[n:] |
| 562 | if kinds(rows) != push.KindActivityUpdate || !strings.Contains(rows[0].Payload, `"stage":"in_review"`) || rows[0].Target != push.TargetActivity { |
| 563 | t.Fatalf("catch-up %+v", rows) |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | // TestPushFirstDeviceHearsOutcomes: a task already waiting on the person |
| 568 | // when their first device registers sets the badge at once, and its merge |
| 569 | // still pushes Done and the badge. |
| 570 | func TestPushFirstDeviceHearsOutcomes(t *testing.T) { |
| 571 | r := newPushRig(t) |
| 572 | k := r.task("tk1", "Fix login", hkMember) |
| 573 | r.stage(&k, wire.StageReadyToMerge) |
| 574 | r.register(hkMember, "cr_m", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS}) |
| 575 | rows := r.outbox() |
| 576 | if len(rows) != 1 || rows[0].Credential != "cr_m" || rows[0].Payload != `{"aps":{"badge":1}}` { |
| 577 | t.Fatalf("registration badge %+v", rows) |
| 578 | } |
| 579 | r.clear() |
| 580 | r.stage(&k, wire.StageDone) |
| 581 | rows = r.outbox() |
| 582 | if kinds(rows) != "badge passive" || rows[0].Payload != `{"aps":{"badge":0}}` || !strings.Contains(rows[1].Payload, "push.task.done") { |
| 583 | t.Fatalf("outcome %s %+v", kinds(rows), rows) |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | // TestPushNeverFailsTheWrite: push bookkeeping that fails rolls back alone |
| 588 | // and the change commits; nothing pushes. |
| 589 | func TestPushNeverFailsTheWrite(t *testing.T) { |
| 590 | r := newPushRig(t) |
| 591 | k := r.task("tk1", "Fix login", hkOwner) |
| 592 | r.must(r.s.db.G.Exec("DROP TABLE push_tasks").Error) |
| 593 | r.step(&k, "s1", wire.SpecialistEngineering, wire.StepRunning) |
| 594 | if got := r.load("tk1"); got.Revision != k.Revision { |
| 595 | t.Fatalf("the task write did not commit: revision %d, want %d", got.Revision, k.Revision) |
| 596 | } |
| 597 | if len(r.outbox()) != 0 { |
| 598 | t.Fatal("a failed push left rows") |
| 599 | } |
| 600 | // A reply whose message cannot be read: the turn is still saved. |
| 601 | r.must(r.tx(func(t *txn) error { |
| 602 | turn := turnRecord{ID: "t1", Person: hkOwner, State: wire.TurnRunning, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now} |
| 603 | if err := t.db.Create(&turn).Error; err != nil { |
| 604 | return err |
| 605 | } |
| 606 | turn.State, turn.ReplyID = wire.TurnReplied, "m_missing" |
| 607 | return t.saveTurn(&turn) |
| 608 | })) |
| 609 | var turn turnRecord |
| 610 | r.must(r.s.db.G.Where("id = ?", "t1").Take(&turn).Error) |
| 611 | if turn.State != wire.TurnReplied { |
| 612 | t.Fatal("the turn was not saved") |
| 613 | } |
| 614 | // Push work that wrote before it failed (the card's once-only mark, |
| 615 | // then no outbox) is undone, and the card is still written. |
| 616 | r.must(r.s.db.G.Exec("DROP TABLE push_outbox").Error) |
| 617 | r.card("c1", wire.CardOpen) |
| 618 | if r.count("SELECT count(*) FROM chat_cards WHERE id = 'c1'") != 1 || r.count("SELECT count(*) FROM push_once") != 0 { |
| 619 | t.Fatal("a failed push kept its part, or lost the card") |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | // TestPushStartsOnlyWhereItCan: with no device that can start a Live |
| 624 | // Activity (a Mac only), a dispatch ends no older activity to make room. |
| 625 | func TestPushStartsOnlyWhereItCan(t *testing.T) { |
| 626 | r := newPushRig(t) |
| 627 | for _, id := range []string{"tk1", "tk2", "tk3"} { |
| 628 | k := r.task(id, "Task "+id, hkOwner) |
| 629 | r.step(&k, "s"+id, wire.SpecialistEngineering, wire.StepRunning) |
| 630 | } |
| 631 | r.must(r.s.db.G.Where("credential = ?", "cr_phone").Delete(&push.Registration{}).Error) |
| 632 | r.register(hkOwner, "cr_mac", wire.RegisterPush{Token: pushMac, Environment: wire.APNsProduction, Platform: wire.PlatformMacOS}) |
| 633 | r.clear() |
| 634 | k := r.task("tk4", "Task tk4", hkOwner) |
| 635 | r.step(&k, "stk4", wire.SpecialistEngineering, wire.StepRunning) |
| 636 | for _, row := range r.outbox() { |
| 637 | if row.Kind == push.KindActivityEnd { |
| 638 | t.Fatalf("ended %s to make room for an activity that never starts", row.TaskID) |
| 639 | } |
| 640 | } |
| 641 | live, err := push.LiveTasks(r.s.db.G, hkOwner) |
| 642 | if err != nil || len(live) != 3 { |
| 643 | t.Fatalf("live %+v %v", live, err) |
| 644 | } |
| 645 | } |
| 646 | |