oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "slices"
8
9 "amadan.net/oficina/equipo/internal/equipo/push"
10 "amadan.net/oficina/equipo/internal/wire"
11 "gorm.io/gorm"
12)
13
14// Push (native slice 2): the engine writes push_outbox rows in the
15// transaction of the change that pushes (push.Rules decides), for the
16// person's registered devices that are still current. The outbox is
17// written only while the instance has a push transport (SetPush).
18//
19// A push is never worth an engine write: the push work of a change runs
20// in a savepoint (pushSafe), and when it fails (a lookup, a seal, a reply
21// that cannot be read) only it is rolled back and logged, without tokens
22// or text, and the change commits without its pushes. Tokens and
23// payloads are sealed at rest (push.Box), so neither is ever SQL text.
24
25// SetPush turns the outbox on: the serve path does, once it built a
26// transport; a seed, a one-shot or a test that does not never writes it.
27func (s *Store) SetPush(on bool) { s.pushOn.Store(on) }
28
29// PushWake is woken after a commit that wrote pushes.
30func (s *Store) PushWake() <-chan struct{} { return s.pushWake }
31
32func (s *Store) wakePush() {
33 select {
34 case s.pushWake <- struct{}{}:
35 default:
36 }
37}
38
39// pushBox seals push's tokens and payloads with the instance key.
40func (s *Store) pushBox() push.Box {
41 return push.Box{Seal: s.authority.Seal, Open: s.authority.Open}
42}
43
44// PushSender drains this store's outbox through tr.
45func (s *Store) PushSender(tr push.Transport) *push.Sender {
46 return &push.Sender{Transport: tr, Now: s.now, Check: s.pushCurrent, Box: s.pushBox(),
47 Write: func(ctx context.Context, fn func(*gorm.DB) error) error {
48 return s.tx(ctx, func(t *txn) error { return fn(t.db) })
49 },
50 Errorf: s.pushWarn}
51}
52
53func (s *Store) pushWarn(msg string, args ...any) {
54 if l := s.logger.Load(); l != nil {
55 l.Warn(msg, args...)
56 }
57}
58
59// pushCurrent: the person is an active member and the device credential
60// still valid (Authority.PushDevice). push.ErrGone when the person left
61// or the device was revoked; push.ErrNotCurrent when it cannot take a
62// push now; another error is a lookup that failed.
63func (s *Store) pushCurrent(tx *gorm.DB, person, credential string) error {
64 var n int64
65 if err := tx.Raw("SELECT count(*) FROM members WHERE address = ? AND active = 1", person).Scan(&n).Error; err != nil {
66 return err
67 }
68 if n != 1 {
69 return push.ErrGone
70 }
71 if s.authority.PushDevice == nil {
72 return push.ErrNotCurrent
73 }
74 return s.authority.PushDevice(tx, person, credential)
75}
76
77// RegisterPush is POST /api/v1/push-registrations: the device credential's
78// registration, replacing its earlier one and taking its tokens from any
79// other credential. Audited without its tokens. With the outbox on, the
80// device hears the badge at once, and what the person's open tasks show
81// now is remembered, so their outcomes push even when this is the first
82// device the person registered.
83func (s *Store) RegisterPush(ctx context.Context, person, credential string, in wire.RegisterPush) (out wire.PushRegistration, err error) {
84 if in.ActionsVersion != 0 && !s.NotificationActions() {
85 return out, ErrForbidden
86 }
87 if credential == "" {
88 return out, ErrForbidden
89 }
90 if push.Validate(in) != nil {
91 return out, ErrInvalid
92 }
93 err = s.tx(ctx, func(t *txn) error {
94 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
95 return err
96 }
97 if err := s.pushCurrent(t.db, person, credential); err != nil {
98 return ErrForbidden
99 }
100 if out, err = push.Register(t.db, s.pushBox(), person, credential, in, t.now()); err != nil {
101 return err
102 }
103 if err := s.authority.Audit(t.db, person, "push.register", credential); err != nil {
104 return err
105 }
106 if !s.pushOn.Load() {
107 return nil
108 }
109 if err := t.pushSeed(person); err != nil {
110 return err
111 }
112 device, err := push.Device(t.db, person, credential)
113 if err != nil {
114 return err
115 }
116 _, err = t.enqueuePush(person, device, push.Badge())
117 return err
118 })
119 return out, err
120}
121
122// pushSeed remembers what the person's open tasks show now, keeping what
123// their Live Activities were told.
124func (t *txn) pushSeed(person string) error {
125 var rows []taskRecord
126 if err := t.db.Where("creator = ? AND stage NOT IN ?", person, []string{wire.StageDone, wire.StageCancelled}).Order("created_at, id").Limit(wire.MaxTaskList).Find(&rows).Error; err != nil {
127 return err
128 }
129 for _, k := range rows {
130 v, err := t.taskView(k)
131 if err != nil {
132 return err
133 }
134 m, err := push.LoadMemory(t.db, person, k.ID)
135 if err != nil {
136 return err
137 }
138 if err := push.SaveMemory(t.db, person, k.ID, m.Remember(pushTaskOf(v, t.s.authority.Copy)), t.now()); err != nil {
139 return err
140 }
141 }
142 return nil
143}
144
145// RegisterActivity is POST /api/v1/push-registrations/activities: a
146// running Live Activity's token for a task the person started. Once the
147// task ended it is taken only while a push for it still waits to go to
148// the device (its activity's end), which then goes at once; before, the
149// activity hears the task's whole state now, which it may have missed
150// while the server had no token for it.
151func (s *Store) RegisterActivity(ctx context.Context, person, credential string, in wire.RegisterActivity) error {
152 if credential == "" {
153 return ErrForbidden
154 }
155 return s.tx(ctx, func(t *txn) error {
156 if err := s.authority.CurrentPerson(ctx, t.db); err != nil {
157 return err
158 }
159 if err := s.pushCurrent(t.db, person, credential); err != nil {
160 return ErrForbidden
161 }
162 var k taskRecord
163 if err := t.db.Where("id = ? AND creator = ?", in.TaskID, person).Take(&k).Error; errors.Is(err, gorm.ErrRecordNotFound) {
164 return ErrNotFound
165 } else if err != nil {
166 return err
167 }
168 ended := wire.FinalStage(k.Stage)
169 if ended {
170 waiting, err := push.Waiting(t.db, credential, k.ID)
171 if err != nil {
172 return err
173 }
174 if !waiting {
175 return ErrTaskEnded
176 }
177 }
178 if err := push.RegisterActivity(t.db, s.pushBox(), person, credential, k.ID, in.Token, t.now()); errors.Is(err, push.ErrInvalid) {
179 return ErrInvalid
180 } else if err != nil {
181 return err
182 }
183 if err := s.authority.Audit(t.db, person, "push.activity", credential+" "+k.ID); err != nil {
184 return err
185 }
186 if ended {
187 t.pushed = true
188 return push.Hurry(t.db, credential, k.ID, t.now())
189 }
190 if !s.pushOn.Load() {
191 return nil
192 }
193 return t.pushCatchUp(person, credential, k)
194 })
195}
196
197// pushCatchUp sends a running activity its task's whole state, to the
198// device whose token just arrived, and remembers the activity running.
199func (t *txn) pushCatchUp(person, credential string, k taskRecord) error {
200 m, err := push.LoadMemory(t.db, person, k.ID)
201 if err != nil {
202 return err
203 }
204 if m.Ended {
205 // A late token for a replaced activity can deliver its end, but
206 // must never revive the activity or enqueue a catch-up update.
207 t.pushed = true
208 return push.Hurry(t.db, credential, k.ID, t.now())
209 }
210 v, err := t.taskView(k)
211 if err != nil {
212 return err
213 }
214 after := pushTaskOf(v, t.s.authority.Copy)
215 device, err := push.Device(t.db, person, credential)
216 if err != nil {
217 return err
218 }
219 if _, err := t.enqueuePush(person, device, push.CatchUp(after)); err != nil {
220 return err
221 }
222 now := t.now()
223 next := m.Remember(after)
224 if !m.Live() {
225 next.Started, next.Ended = &now, false
226 }
227 return push.SaveMemory(t.db, person, k.ID, next, now)
228}
229
230// pushSafe runs a change's push work in a savepoint while the outbox is
231// on: its failure rolls back only the push work, is logged, and never
232// fails the change.
233func (t *txn) pushSafe(what string, fn func() error) error {
234 if !t.s.pushOn.Load() {
235 return nil
236 }
237 if err := t.db.SavePoint("push").Error; err != nil {
238 t.s.pushWarn("push skipped", "change", what, "err", err)
239 return nil
240 }
241 if err := fn(); err != nil {
242 if rerr := t.db.RollbackTo("push").Error; rerr != nil {
243 return rerr
244 }
245 t.s.pushWarn("push skipped", "change", what, "err", err)
246 }
247 return nil
248}
249
250// pushDevices are the person's current registrations, none while the
251// outbox is off.
252func (t *txn) pushDevices(person string) ([]push.Registration, error) {
253 if !t.s.pushOn.Load() || person == "" {
254 return nil, nil
255 }
256 all, err := push.Devices(t.db, person)
257 if err != nil || len(all) == 0 {
258 return nil, err
259 }
260 var out []push.Registration
261 for _, d := range all {
262 if t.s.pushCurrent(t.db, person, d.Credential) == nil {
263 out = append(out, d)
264 }
265 }
266 return out, nil
267}
268
269// enqueuePush writes an intent's rows, one a device that can take it,
270// and reports how many. A payload over APNs' limit is no push.
271func (t *txn) enqueuePush(person string, devices []push.Registration, in push.Intent) (int, error) {
272 if len(devices) == 0 {
273 return 0, nil
274 }
275 badge := 0
276 if in.Kind == push.KindBadge {
277 n, err := t.needsYouCount(person)
278 if err != nil {
279 return 0, err
280 }
281 badge = n
282 }
283 now := t.now()
284 in.Origin = t.s.authority.Origin
285 raw, typ, err := push.Render(in, t.s.authority.Copy, badge, now)
286 if errors.Is(err, push.ErrTooLarge) {
287 t.s.pushWarn("push too large", "rule", in.Rule, "task", in.TaskID)
288 return 0, nil
289 }
290 if err != nil {
291 return 0, err
292 }
293 written := 0
294 for _, d := range devices {
295 target := push.TargetDevice
296 switch in.Kind {
297 case push.KindActivityStart:
298 if !startable(d) {
299 continue
300 }
301 target = push.TargetStart
302 case push.KindActivityUpdate, push.KindActivityEnd:
303 has, err := push.HasActivity(t.db, d.Credential, in.TaskID)
304 if err != nil {
305 return written, err
306 }
307 // An update needs the activity's own token: without it the row
308 // would only be dropped, and the activity hears the whole state
309 // when its token arrives (pushCatchUp). An end waits a while
310 // for the token.
311 if d.Platform != wire.PlatformIOS || !has && (in.Kind == push.KindActivityUpdate || d.StartToken == "") {
312 continue
313 }
314 target = push.TargetActivity
315 }
316 // Add bindings per opted-in registration. An oversized enrichment keeps
317 // the original alert, never a partial or actionable unbound payload.
318 deviceRaw := raw
319 enriched := t.notificationIntent(in, d)
320 if enriched.Data.Actions != nil {
321 if candidate, _, renderErr := push.Render(enriched, t.s.authority.Copy, badge, now); renderErr == nil {
322 deviceRaw = candidate
323 }
324 }
325 r := push.OutboxRecord{Person: person, Credential: d.Credential, Kind: in.Kind, Target: target, TaskID: in.TaskID, PushType: typ, Priority: in.Priority, CollapseID: in.CollapseID, Dedupe: in.Dedupe, Payload: string(deviceRaw), NextAt: now, CreatedAt: now, UpdatedAt: now}
326 if err := push.Enqueue(t.db, t.s.pushBox(), r, in.Coalesce); err != nil {
327 return written, err
328 }
329 written++
330 }
331 if written > 0 {
332 t.pushed = true
333 }
334 return written, nil
335}
336
337// startable: the device can start a Live Activity by push.
338func startable(d push.Registration) bool {
339 return d.Platform == wire.PlatformIOS && d.StartToken != ""
340}
341
342// needsYouCount is the person's Needs you count (GET /needs-you), for the
343// badge. An error stays an error: never a zero.
344func (t *txn) needsYouCount(person string) (int, error) {
345 var rows []taskRecord
346 if err := t.db.Where("creator = ? AND stage NOT IN ?", person, []string{wire.StageDone, wire.StageCancelled}).Limit(wire.MaxTaskList).Find(&rows).Error; err != nil {
347 return 0, err
348 }
349 n := 0
350 for _, k := range rows {
351 v, err := t.taskView(k)
352 if err != nil {
353 return 0, err
354 }
355 if v.NeedsYou != "" {
356 n++
357 }
358 }
359 return n, nil
360}
361
362// pushIntents writes each intent for the person's devices, and reports
363// the rows written. A once-only intent is decided once for the person,
364// devices or not (push_once), and never again.
365func (t *txn) pushIntents(person string, devices []push.Registration, intents []push.Intent) (int, error) {
366 written := 0
367 for _, in := range intents {
368 if in.Dedupe != "" {
369 first, err := push.Once(t.db, person, in.Dedupe, t.now())
370 if err != nil {
371 return written, err
372 }
373 if !first {
374 continue
375 }
376 }
377 n, err := t.enqueuePush(person, devices, in)
378 if err != nil {
379 return written, err
380 }
381 written += n
382 }
383 return written, nil
384}
385
386// pushCard: a card that waits on its person opened. Its alert is decided
387// even with no device registered, so a card opened before a device was
388// never alerts later.
389func (t *txn) pushCard(c cardRecord, v wire.Card) error {
390 return t.pushSafe("card", func() error {
391 card := push.Card{ID: c.ID, Kind: c.Kind, State: c.State, Lane: c.Lane, Question: v.Question, TaskID: c.TaskID, AccessFinal: v.Access != nil && wire.AccessFinal(v.Access.State)}
392 intents := push.Decide(push.Change{Kind: push.ChangeCard, Now: t.now(), Card: card})
393 if len(intents) == 0 {
394 return nil
395 }
396 devices, err := t.pushDevices(c.Person)
397 if err != nil {
398 return err
399 }
400 _, err = t.pushIntents(c.Person, devices, intents)
401 return err
402 })
403}
404
405// pushReply: the coordinator's turn ended.
406func (t *txn) pushReply(r turnRecord) error {
407 if r.State != wire.TurnReplied || r.ReplyID == "" {
408 return nil
409 }
410 return t.pushSafe("reply", func() error {
411 devices, err := t.pushDevices(r.Person)
412 if err != nil || len(devices) == 0 {
413 return err
414 }
415 var m messageRecord
416 if err := t.db.Where("id = ? AND person = ?", r.ReplyID, r.Person).Take(&m).Error; err != nil {
417 return err
418 }
419 reply := push.Reply{TurnID: r.ID, Lane: r.Lane, Kind: r.Kind, State: r.State, Text: m.Text}
420 _, err = t.pushIntents(r.Person, devices, push.Decide(push.Change{Kind: push.ChangeReply, Now: t.now(), Reply: reply, Streaming: t.s.hub.Streaming(r.Person)}))
421 return err
422 })
423}
424
425// pushTask: a task was written; its creator's devices hear what changed.
426func (t *txn) pushTask(v wire.Task) error {
427 return t.pushSafe("task", func() error {
428 devices, err := t.pushDevices(v.Creator)
429 if err != nil || len(devices) == 0 {
430 return err
431 }
432 before, err := push.LoadMemory(t.db, v.Creator, v.ID)
433 if err != nil {
434 return err
435 }
436 after := pushTaskOf(v, t.s.authority.Copy)
437 now := t.now()
438 next := before.Remember(after)
439 for _, in := range push.Decide(push.Change{Kind: push.ChangeTask, Now: now, Before: before, After: after}) {
440 if in.Kind == push.KindActivityStart {
441 if !slices.ContainsFunc(devices, startable) {
442 continue
443 }
444 if err := t.pushMakeRoom(v.Creator, devices); err != nil {
445 return err
446 }
447 }
448 n, err := t.pushIntents(v.Creator, devices, []push.Intent{in})
449 if err != nil {
450 return err
451 }
452 switch {
453 case in.Kind == push.KindActivityStart && n > 0:
454 next.Started, next.Ended = &now, false
455 case in.Kind == push.KindActivityEnd:
456 next.Ended = true
457 }
458 }
459 return push.SaveMemory(t.db, v.Creator, v.ID, next, now)
460 })
461}
462
463// pushMakeRoom ends the oldest Live Activities so a new one is at most
464// wire.MaxLiveActivities.
465func (t *txn) pushMakeRoom(person string, devices []push.Registration) error {
466 live, err := push.LiveTasks(t.db, person)
467 if err != nil {
468 return err
469 }
470 for len(live) >= wire.MaxLiveActivities {
471 old := live[0]
472 live = live[1:]
473 m, err := push.LoadMemory(t.db, person, old.TaskID)
474 if err != nil {
475 return err
476 }
477 if _, err := t.enqueuePush(person, devices, push.Replace(m.Task(old.TaskID))); err != nil {
478 return err
479 }
480 m.Ended = true
481 if err := push.SaveMemory(t.db, person, old.TaskID, m, t.now()); err != nil {
482 return err
483 }
484 }
485 return nil
486}
487
488// pushLine: a running step of a task reported an activity line. Only a
489// line some device was sent is remembered as told.
490func (t *txn) pushLine(s stepRecord, line wire.ActivityLine) error {
491 return t.pushSafe("line", func() error {
492 var k taskRecord
493 if err := t.db.Where("id = ?", s.TaskID).Take(&k).Error; err != nil {
494 return err
495 }
496 devices, err := t.pushDevices(k.Creator)
497 if err != nil || len(devices) == 0 {
498 return err
499 }
500 before, err := push.LoadMemory(t.db, k.Creator, k.ID)
501 if err != nil || !before.Live() {
502 return err
503 }
504 after := before.Task(k.ID)
505 after.Activity = activityLine(line, t.s.authority.Copy)
506 now := t.now()
507 intents := push.Decide(push.Change{Kind: push.ChangeLine, Now: now, Before: before, After: after})
508 if len(intents) == 0 {
509 return nil
510 }
511 n, err := t.pushIntents(k.Creator, devices, intents)
512 if err != nil || n == 0 {
513 return err
514 }
515 next := before.Remember(after)
516 next.LineAt = &now
517 return push.SaveMemory(t.db, k.Creator, k.ID, next, now)
518 })
519}
520
521// pushTaskOf is a task as its Live Activity shows it: the step working
522// now (running or queued, else the last done), its newest line, and
523// Roster's tone.
524func pushTaskOf(v wire.Task, copy func(string) string) push.Task {
525 k := push.Task{ID: v.ID, Title: v.Title, Stage: v.Stage, NeedsYou: v.NeedsYou, Tone: wire.TonePositive}
526 steps := v.Steps
527 var current *wire.Step
528 for j := len(steps) - 1; j >= 0 && current == nil; j-- {
529 if steps[j].State == wire.StepRunning || steps[j].State == wire.StepQueued {
530 current = &steps[j]
531 }
532 }
533 for j := len(steps) - 1; j >= 0 && current == nil; j-- {
534 if steps[j].State == wire.StepDone {
535 current = &steps[j]
536 }
537 }
538 // No step working or done (Design's first attempt failed or was
539 // cancelled): the task's maker, not the apps' Engineering default.
540 k.Specialist = v.Maker.Category()
541 if current != nil {
542 k.Specialist, k.StepID = current.Specialist, current.ID
543 if c := current.Maker.Category(); c != "" {
544 // Design works on Engineering's step kind, as itself.
545 k.Specialist = c
546 }
547 if current.State == wire.StepRunning {
548 k.Working = true
549 k.Activity = copy("work.activity.working")
550 if n := len(current.Activity); n > 0 {
551 k.Activity = activityLine(current.Activity[n-1], copy)
552 }
553 }
554 }
555 switch {
556 case v.Checks == wire.ChecksFailed || v.Verdict == wire.VerdictChanges:
557 k.Tone = wire.ToneNegative
558 case v.NeedsYou != "":
559 k.Tone = wire.ToneWarning
560 }
561 return k
562}
563
564// activityLine is a step's activity line in words (the web's
565// activityText).
566func activityLine(a wire.ActivityLine, copy func(string) string) string {
567 format := copy("work.activity." + a.Kind)
568 if a.Subject == "" || a.Kind == wire.ActivityOther || format == "" {
569 return copy("work.activity.working")
570 }
571 return push.Clip(fmt.Sprintf(format, a.Subject))
572}
573