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 "crypto/rand"
5 "errors"
6 "fmt"
7 "regexp"
8 "strings"
9 "time"
10
11 "amadan.net/oficina/equipo/internal/wire"
12 "gorm.io/gorm"
13 "gorm.io/gorm/clause"
14)
15
16// Models are the push tables, for the migration check (chat.Models
17// carries them).
18var Models = []any{&Registration{}, &ActivityToken{}, &OutboxRecord{}, &MemoryRecord{}, &OnceRecord{}, &HoldRecord{}}
19
20// Registration is a paired device's push registration, one per device
21// credential: a new one replaces it, and one APNs token belongs to one
22// credential (the newest to register it). Token and StartToken are sealed
23// (Box); Registrations from Devices hold them sealed.
24type Registration struct {
25 ActionsVersion int
26 BindingID string
27 Credential string `gorm:"primaryKey"`
28 Person string `gorm:"index:push_registration_person"`
29 Token string
30 Environment string
31 Platform string
32 StartToken string
33 CreatedAt time.Time
34 UpdatedAt time.Time
35}
36
37func (Registration) TableName() string { return "push_registrations" }
38
39// ActivityToken is a running Live Activity's own update token, on one
40// device, for one task; Token is sealed.
41type ActivityToken struct {
42 Credential string `gorm:"primaryKey"`
43 TaskID string `gorm:"primaryKey"`
44 Person string `gorm:"index:push_activity_person"`
45 Token string
46 CreatedAt time.Time
47}
48
49func (ActivityToken) TableName() string { return "push_activities" }
50
51// Outbox row states.
52const (
53 StatePending = "pending"
54 StateSent = "sent"
55 StateFailed = "failed"
56 // StateDropped: never sent, because the device or person is gone or
57 // no token was ever on file.
58 StateDropped = "dropped"
59)
60
61// OutboxRecord is one push to one device. The token is not copied here:
62// the sender reads it from the registration when it sends, so a revoked
63// device or a replaced token never receives an old row. ID is a canonical
64// lowercase UUID, sent as apns-id; Payload is sealed (Box).
65type OutboxRecord struct {
66 ID string `gorm:"primaryKey"`
67 Person string `gorm:"index:push_outbox_person"`
68 Credential string `gorm:"index:push_outbox_credential"`
69 Kind string
70 Target string
71 TaskID string
72 PushType string
73 Priority int
74 CollapseID string
75 Dedupe string `gorm:"index:push_outbox_dedupe"`
76 Payload string
77 State string `gorm:"index:push_outbox_due,priority:1"`
78 NextAt time.Time `gorm:"index:push_outbox_due,priority:2"`
79 Attempts int
80 LeaseUntil *time.Time
81 // Apple's answer to the newest send.
82 Status int
83 Reason string
84 APNsID string `gorm:"column:apns_id"`
85 SentAt *time.Time
86 CreatedAt time.Time
87 UpdatedAt time.Time
88}
89
90func (OutboxRecord) TableName() string { return "push_outbox" }
91
92// MemoryRecord is what a person's devices were last told about a task
93// they started (Memory).
94type MemoryRecord struct {
95 Person string `gorm:"primaryKey"`
96 TaskID string `gorm:"primaryKey"`
97 Title string
98 Tone string
99 Stage string
100 NeedsYou string
101 Specialist string
102 StepID string
103 Activity string
104 StartedAt *time.Time
105 Ended bool
106 LineAt *time.Time
107 UpdatedAt time.Time
108}
109
110func (MemoryRecord) TableName() string { return "push_tasks" }
111
112// OnceRecord marks a once-only push (a card's alert, a reply's, a task's
113// outcome) as decided for a person, whether or not a device took it. It
114// is kept while the person is, never pruned with the outbox, so a card
115// alerts once in its life.
116type OnceRecord struct {
117 Person string `gorm:"primaryKey"`
118 Key string `gorm:"primaryKey"`
119 CreatedAt time.Time
120}
121
122func (OnceRecord) TableName() string { return "push_once" }
123
124// ErrInvalid is a registration the server refuses.
125var ErrInvalid = errors.New("push: invalid registration")
126
127func hexToken(s string) bool {
128 if len(s) < 32 || len(s) > wire.MaxPushToken || len(s)%2 != 0 {
129 return false
130 }
131 for _, r := range s {
132 if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r >= 'A' && r <= 'F') {
133 return false
134 }
135 }
136 return true
137}
138
139// Validate checks a registration: hex tokens, a known environment and
140// platform, and a push-to-start token only on iPhone.
141var actionBindingPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
142
143func ValidActionBinding(id string) bool { return actionBindingPattern.MatchString(id) }
144
145func Validate(in wire.RegisterPush) error {
146 if (in.ActionsVersion != 0 && in.ActionsVersion != 1) ||
147 (in.ActionsVersion == 0 && in.BindingID != "") ||
148 (in.ActionsVersion == 1 && !ValidActionBinding(in.BindingID)) {
149 return ErrInvalid
150 }
151 if !hexToken(in.Token) || in.StartToken != "" && !hexToken(in.StartToken) {
152 return ErrInvalid
153 }
154 if in.Environment != wire.APNsProduction && in.Environment != wire.APNsDevelopment {
155 return ErrInvalid
156 }
157 if in.Platform != wire.PlatformIOS && in.Platform != wire.PlatformMacOS || in.Platform == wire.PlatformMacOS && in.StartToken != "" {
158 return ErrInvalid
159 }
160 return nil
161}
162
163// Register replaces the credential's registration. A token another
164// credential holds (the phone signed out offline and paired again, maybe
165// as someone else) is taken from it: that credential's registration, what
166// waits for it and its activity tokens holding the token go.
167func Register(tx *gorm.DB, box Box, person, credential string, in wire.RegisterPush, now time.Time) (wire.PushRegistration, error) {
168 if err := Validate(in); err != nil {
169 return wire.PushRegistration{}, err
170 }
171 token, start := strings.ToLower(in.Token), strings.ToLower(in.StartToken)
172 mine := map[string]bool{token: true}
173 if start != "" {
174 mine[start] = true
175 }
176 if err := takeTokens(tx, box, credential, mine); err != nil {
177 return wire.PushRegistration{}, err
178 }
179 sealed, err := box.seal(domainToken, token)
180 if err != nil {
181 return wire.PushRegistration{}, err
182 }
183 sealedStart, err := box.seal(domainToken, start)
184 if err != nil {
185 return wire.PushRegistration{}, err
186 }
187 r := Registration{ActionsVersion: in.ActionsVersion, BindingID: in.BindingID, Credential: credential, Person: person, Token: sealed, Environment: in.Environment, Platform: in.Platform, StartToken: sealedStart, CreatedAt: now, UpdatedAt: now}
188 err = tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "credential"}}, DoUpdates: clause.AssignmentColumns([]string{"person", "token", "environment", "platform", "start_token", "updated_at", "actions_version", "binding_id"})}).Create(&r).Error
189 return wire.PushRegistration{Environment: r.Environment, Platform: r.Platform, LiveActivities: start != "", UpdatedAt: now}, err
190}
191
192// takeTokens forgets every other credential's registration holding one of
193// the tokens, and every other credential's activity token that is one.
194// Tokens are sealed, so they are compared opened, in Go: never in SQL. A
195// token that will not open cannot be this one, and never stops a
196// registration.
197func takeTokens(tx *gorm.DB, box Box, credential string, tokens map[string]bool) error {
198 var regs []Registration
199 if err := tx.Where("credential <> ?", credential).Find(&regs).Error; err != nil {
200 return err
201 }
202 for _, r := range regs {
203 for _, sealed := range []string{r.Token, r.StartToken} {
204 t, err := box.open(domainToken, sealed)
205 if err == nil && t != "" && tokens[t] {
206 if err := ForgetCredential(tx, r.Credential); err != nil {
207 return err
208 }
209 break
210 }
211 }
212 }
213 var acts []ActivityToken
214 if err := tx.Where("credential <> ?", credential).Find(&acts).Error; err != nil {
215 return err
216 }
217 for _, a := range acts {
218 t, err := box.open(domainToken, a.Token)
219 if err == nil && tokens[t] {
220 if err := tx.Where("credential = ? AND task_id = ?", a.Credential, a.TaskID).Delete(&ActivityToken{}).Error; err != nil {
221 return err
222 }
223 }
224 }
225 return nil
226}
227
228// RegisterActivity keeps a running activity's update token, taken from
229// any other credential that held it.
230func RegisterActivity(tx *gorm.DB, box Box, person, credential, task, token string, now time.Time) error {
231 if !hexToken(token) || task == "" {
232 return ErrInvalid
233 }
234 token = strings.ToLower(token)
235 if err := takeTokens(tx, box, credential, map[string]bool{token: true}); err != nil {
236 return err
237 }
238 sealed, err := box.seal(domainToken, token)
239 if err != nil {
240 return err
241 }
242 a := ActivityToken{Credential: credential, TaskID: task, Person: person, Token: sealed, CreatedAt: now}
243 return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "credential"}, {Name: "task_id"}}, DoUpdates: clause.AssignmentColumns([]string{"person", "token", "created_at"})}).Create(&a).Error
244}
245
246// Waiting reports whether a push for the task still waits to go to the
247// device (an activity's end waiting for its token).
248func Waiting(tx *gorm.DB, credential, task string) (bool, error) {
249 var n int64
250 err := tx.Model(&OutboxRecord{}).Where("credential = ? AND task_id = ? AND state = ?", credential, task, StatePending).Count(&n).Error
251 return n > 0, err
252}
253
254// Hurry makes activity updates and ends due now: their token just arrived.
255// A start's Apple retry deadline must stay intact.
256func Hurry(tx *gorm.DB, credential, task string, now time.Time) error {
257 return tx.Model(&OutboxRecord{}).Where("credential = ? AND task_id = ? AND target = ? AND state = ? AND lease_until IS NULL", credential, task, TargetActivity, StatePending).Select("next_at").Updates(map[string]any{"next_at": now}).Error
258}
259
260// ForgetCredential deletes a device's registration, its activity tokens
261// and what still waits to go to it: the device was revoked, or Apple said
262// its token is gone.
263func ForgetCredential(tx *gorm.DB, credential string) error {
264 if err := tx.Where("credential = ?", credential).Delete(&Registration{}).Error; err != nil {
265 return err
266 }
267 if err := tx.Where("credential = ?", credential).Delete(&ActivityToken{}).Error; err != nil {
268 return err
269 }
270 return tx.Model(&OutboxRecord{}).Where("credential = ? AND state = ?", credential, StatePending).Select("state", "reason", "lease_until").Updates(map[string]any{"state": StateDropped, "reason": "forgotten", "lease_until": nil}).Error
271}
272
273// ForgetPerson deletes everything push holds for a person removed from the
274// roster.
275func ForgetPerson(tx *gorm.DB, person string) error {
276 for _, m := range []any{&Registration{}, &ActivityToken{}, &MemoryRecord{}, &OnceRecord{}} {
277 if err := tx.Where("person = ?", person).Delete(m).Error; err != nil {
278 return err
279 }
280 }
281 return tx.Model(&OutboxRecord{}).Where("person = ? AND state = ?", person, StatePending).Select("state", "reason", "lease_until").Updates(map[string]any{"state": StateDropped, "reason": "forgotten", "lease_until": nil}).Error
282}
283
284// Devices are the person's registrations, oldest first, their tokens
285// sealed.
286func Devices(tx *gorm.DB, person string) ([]Registration, error) {
287 var out []Registration
288 err := tx.Where("person = ?", person).Order("created_at, credential").Find(&out).Error
289 return out, err
290}
291
292// Device is one credential's registration, its tokens sealed.
293func Device(tx *gorm.DB, person, credential string) ([]Registration, error) {
294 var out []Registration
295 err := tx.Where("person = ? AND credential = ?", person, credential).Find(&out).Error
296 return out, err
297}
298
299// HasActivity reports whether a device has a running activity's token for
300// the task.
301func HasActivity(tx *gorm.DB, credential, task string) (bool, error) {
302 var n int64
303 err := tx.Model(&ActivityToken{}).Where("credential = ? AND task_id = ?", credential, task).Count(&n).Error
304 return n > 0, err
305}
306
307// LoadMemory is the person's memory of a task (Seen false when none).
308func LoadMemory(tx *gorm.DB, person, task string) (Memory, error) {
309 var r MemoryRecord
310 err := tx.Where("person = ? AND task_id = ?", person, task).Take(&r).Error
311 if errors.Is(err, gorm.ErrRecordNotFound) {
312 return Memory{}, nil
313 }
314 if err != nil {
315 return Memory{}, err
316 }
317 return Memory{Seen: true, Title: r.Title, Tone: r.Tone, Stage: r.Stage, NeedsYou: r.NeedsYou, Specialist: r.Specialist, StepID: r.StepID, Activity: r.Activity, Started: r.StartedAt, Ended: r.Ended, LineAt: r.LineAt}, nil
318}
319
320// SaveMemory records what the devices were told about a task.
321func SaveMemory(tx *gorm.DB, person, task string, m Memory, now time.Time) error {
322 r := MemoryRecord{Person: person, TaskID: task, Title: m.Title, Tone: m.Tone, Stage: m.Stage, NeedsYou: m.NeedsYou, Specialist: m.Specialist, StepID: m.StepID, Activity: m.Activity, StartedAt: m.Started, Ended: m.Ended, LineAt: m.LineAt, UpdatedAt: now}
323 return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "person"}, {Name: "task_id"}}, DoUpdates: clause.AssignmentColumns([]string{"title", "tone", "stage", "needs_you", "specialist", "step_id", "activity", "started_at", "ended", "line_at", "updated_at"})}).Create(&r).Error
324}
325
326// LiveTasks are the tasks with a running Live Activity for the person,
327// oldest start first.
328func LiveTasks(tx *gorm.DB, person string) ([]MemoryRecord, error) {
329 var out []MemoryRecord
330 err := tx.Where("person = ? AND started_at IS NOT NULL AND ended = ?", person, false).Order("started_at, task_id").Find(&out).Error
331 return out, err
332}
333
334// Enqueue writes one row, its payload sealed: over an unsent one with
335// the same collapse ID when it coalesces.
336func Enqueue(tx *gorm.DB, box Box, r OutboxRecord, coalesce bool) error {
337 if len(r.Payload) > MaxPayload {
338 return ErrTooLarge
339 }
340 sealed, err := box.seal(domainPayload, r.Payload)
341 if err != nil {
342 return err
343 }
344 r.Payload = sealed
345 if coalesce {
346 res := tx.Model(&OutboxRecord{}).Where("credential = ? AND collapse_id = ? AND state = ? AND lease_until IS NULL", r.Credential, r.CollapseID, StatePending).Select("payload", "priority", "next_at", "updated_at").Updates(map[string]any{"payload": r.Payload, "priority": r.Priority, "next_at": r.NextAt, "updated_at": r.UpdatedAt})
347 if res.Error != nil || res.RowsAffected > 0 {
348 return res.Error
349 }
350 }
351 r.ID = NewID()
352 r.State = StatePending
353 return tx.Create(&r).Error
354}
355
356// NewID is a row ID: a random (version 4) UUID, canonical and lowercase,
357// as apns-id must be.
358func NewID() string {
359 var b [16]byte
360 _, _ = rand.Read(b[:])
361 b[6] = b[6]&0x0f | 0x40
362 b[8] = b[8]&0x3f | 0x80
363 return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
364}
365
366// Once marks a once-only push decided for the person, and reports
367// whether this is the first time.
368func Once(tx *gorm.DB, person, key string, now time.Time) (bool, error) {
369 res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&OnceRecord{Person: person, Key: key, CreatedAt: now})
370 return res.RowsAffected == 1, res.Error
371}
372