| 1 | package notifications |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "gorm.io/gorm" |
| 6 | "gorm.io/gorm/clause" |
| 7 | "strings" |
| 8 | "time" |
| 9 | ) |
| 10 | |
| 11 | // Re-read authority and resource state. A notification never supplies an answer capability. |
| 12 | func (s *Store) current(tx *gorm.DB, n Event) (bool, error) { |
| 13 | if n.State == "superseded" { |
| 14 | return false, nil |
| 15 | } |
| 16 | var count int64 |
| 17 | var q *gorm.DB |
| 18 | switch n.ResourceType { |
| 19 | case "clarification": |
| 20 | q = tx.Table("coordinator_questions q").Joins("JOIN coordinator_bindings b ON b.id=q.binding_id").Where("q.id=? AND q.person=? AND b.team_id=? AND q.revision=? AND q.state='pending' AND q.generation=b.generation AND julianday(json_extract(q.payload,'$.ExpiresAt'))>julianday(?)", n.ResourceID, n.Recipient, n.TeamID, n.ResourceRevision, s.Now().UTC()) |
| 21 | case "question": |
| 22 | q = tx.Table("questions q").Joins("JOIN tasks t ON t.id=q.task_id").Joins("JOIN runner_assignments a ON a.id=q.assignment_id").Joins("JOIN jobs j ON j.id=t.job_id").Joins("JOIN attempts attempt ON attempt.id=q.attempt").Where("t.state NOT IN ('cancelled','cancel_requested','failed','merged') AND j.state NOT IN ('succeeded','cancelled','failed') AND attempt.state='active' AND attempt.fence=q.fence").Where("q.id=? AND t.team_id=? AND q.revision=? AND q.state='pending' AND julianday(q.expires_at)>julianday(?) AND a.state='claimed' AND a.attempt_id=q.attempt AND a.fence=q.fence AND julianday(a.lease_deadline)>julianday(?) AND (t.requester=? OR EXISTS(SELECT 1 FROM decision_owners o WHERE o.project_id=t.project_id AND o.address=?))", n.ResourceID, n.TeamID, n.ResourceRevision, s.Now().UTC(), s.Now().UTC(), n.Recipient, n.Recipient) |
| 23 | case "task": |
| 24 | q = tx.Table("tasks t").Where("t.id=? AND t.team_id=? AND t.revision=? AND t.state NOT IN ('cancelled','cancel_requested','merged','failed') AND (t.requester=? OR EXISTS(SELECT 1 FROM decision_owners o WHERE o.project_id=t.project_id AND o.address=?))", n.ResourceID, n.TeamID, n.ResourceRevision, n.Recipient, n.Recipient) |
| 25 | if strings.HasPrefix(n.Event, "task_ready.decision.") { |
| 26 | q = q.Where("EXISTS(SELECT 1 FROM jobs j WHERE j.id=t.job_id AND j.state='waiting' AND j.wait='approval' AND 'task_ready.decision.'||j.revision=?)", n.Event) |
| 27 | } |
| 28 | if strings.HasPrefix(n.Event, "interrupted.job.") { |
| 29 | q = q.Where("EXISTS(SELECT 1 FROM jobs j WHERE j.id=t.job_id AND j.state='waiting' AND j.wait IN ('uncertain_external_outcome','runner_unavailable','connection_unavailable'))") |
| 30 | } |
| 31 | case "coordinator": |
| 32 | q = tx.Table("coordinator_turns t").Joins("JOIN coordinator_bindings b ON b.id=t.binding_id").Where("t.id=? AND t.team_id=? AND t.person=? AND t.revision=? AND t.generation=b.generation AND t.state IN ('uncertain','fenced','context_limit','context_unavailable')", n.ResourceID, n.TeamID, n.Recipient, n.ResourceRevision) |
| 33 | case "card": |
| 34 | q = tx.Table("conversation_cards k").Joins("JOIN conversations c ON c.id=k.stream_id").Where("k.id=? AND c.team_id=? AND c.person=? AND k.revision=?", n.ResourceID, n.TeamID, n.Recipient, n.ResourceRevision) |
| 35 | default: |
| 36 | return false, nil |
| 37 | } |
| 38 | err := q.Count(&count).Error |
| 39 | return count == 1, err |
| 40 | } |
| 41 | |
| 42 | // Acknowledged history lasts at least thirty days. Pending questions and unread |
| 43 | // entries on any still-valid subscription survive cleanup. |
| 44 | func (s *Store) prune(tx *gorm.DB, team, person string) error { |
| 45 | var rows []Event |
| 46 | now := s.Now().UTC() |
| 47 | if err := tx.Where("team_id=? AND recipient=? AND acknowledged_at<?", team, person, now.Add(-30*24*time.Hour)).Order("sequence").Limit(100).Find(&rows).Error; err != nil { |
| 48 | return err |
| 49 | } |
| 50 | var through int64 |
| 51 | for _, n := range rows { |
| 52 | if n.Kind == "question" { |
| 53 | current, err := s.current(tx, n) |
| 54 | if err != nil { |
| 55 | return err |
| 56 | } |
| 57 | if current { |
| 58 | continue |
| 59 | } |
| 60 | } |
| 61 | var unread int64 |
| 62 | if err := tx.Table("notification_subscriptions s").Joins("JOIN person_devices p ON p.id=s.device_id").Joins("LEFT JOIN notification_deliveries d ON d.subscription_id=s.id AND d.sequence=?", n.Sequence).Where("s.team_id=? AND s.person=? AND s.active=1 AND s.expires_at>? AND p.revoked_at IS NULL AND p.token_expires_at>? AND d.acknowledged_at IS NULL", team, person, now, now).Count(&unread).Error; err != nil { |
| 63 | return err |
| 64 | } |
| 65 | if unread > 0 { |
| 66 | continue |
| 67 | } |
| 68 | if err := tx.Where("sequence=?", n.Sequence).Delete(&Delivery{}).Error; err != nil { |
| 69 | return err |
| 70 | } |
| 71 | if err := tx.Where("sequence=?", n.Sequence).Delete(&Event{}).Error; err != nil { |
| 72 | return err |
| 73 | } |
| 74 | if n.Sequence > through { |
| 75 | through = n.Sequence |
| 76 | } |
| 77 | } |
| 78 | if through == 0 { |
| 79 | return nil |
| 80 | } |
| 81 | h := History{TeamID: team, Person: person, PrunedThrough: through} |
| 82 | return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "team_id"}, {Name: "person"}}, DoUpdates: clause.Assignments(map[string]any{"pruned_through": gorm.Expr("MAX(pruned_through,?)", through)})}).Create(&h).Error |
| 83 | } |
| 84 | func historyAt(tx *gorm.DB, team, person string) (int64, error) { |
| 85 | var h History |
| 86 | err := tx.Where("team_id=? AND person=?", team, person).Take(&h).Error |
| 87 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 88 | err = nil |
| 89 | } |
| 90 | return h.PrunedThrough, err |
| 91 | } |
| 92 | |