oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package notifications
2
3import (
4 "context"
5 "crypto/rand"
6 "errors"
7 "time"
8
9 "amadan.net/oficina/equipo/internal/equipo/kernel"
10 "amadan.net/oficina/equipo/internal/equipo/personapi"
11 "gorm.io/gorm"
12 "gorm.io/gorm/clause"
13)
14
15type Store struct {
16 Write func(context.Context, func(*gorm.DB) error) error
17 Read func(context.Context, func(*gorm.DB) error) error
18 Authorize func(*gorm.DB, kernel.Actor) (string, error)
19 Audit func(*gorm.DB, kernel.Actor, string, string) error
20 Devices func() *personapi.DeviceStore
21 Key func() string
22 Now func() time.Time
23 Invalid, Forbidden, NotFound, Conflict, CursorExpired error
24}
25type position struct {
26 Subscription string
27 After int64
28 History int64
29}
30
31func (s *Store) codec() kernel.CursorCodec { return kernel.CursorCodec{Key: s.Key(), Now: s.Now} }
32func scope(team, person string) string { return "notifications\x00" + team + "\x00" + person }
33func (s *Store) device(tx *gorm.DB, ctx context.Context, a kernel.Actor, id string) (time.Time, error) {
34 var d struct{ TokenExpiresAt time.Time }
35 if err := tx.Table("person_devices").Select("token_expires_at").Where("id=? AND person=?", id, a.Address).Take(&d).Error; err != nil {
36 if errors.Is(err, gorm.ErrRecordNotFound) {
37 return time.Time{}, s.NotFound
38 }
39 return time.Time{}, err
40 }
41 if caller, ok := personapi.PrincipalFrom(ctx); ok && caller.CredentialID != "" && caller.CredentialID != id {
42 return time.Time{}, s.NotFound
43 }
44 if _, err := s.Devices().VerifyAt(tx, id, ""); err != nil {
45 return time.Time{}, personapi.ErrSubscriptionExpired
46 }
47 return d.TokenExpiresAt, nil
48}
49func (s *Store) subscription(tx *gorm.DB, ctx context.Context, a kernel.Actor, team, id string, active bool) (Subscription, error) {
50 var sub Subscription
51 if err := tx.Where("id=? AND team_id=? AND person=?", id, team, a.Address).Take(&sub).Error; err != nil {
52 if errors.Is(err, gorm.ErrRecordNotFound) {
53 return sub, s.NotFound
54 }
55 return sub, err
56 }
57 if _, err := s.device(tx, ctx, a, sub.DeviceID); err != nil {
58 return sub, err
59 }
60 if !s.Now().Before(sub.ExpiresAt) || active && !sub.Active {
61 return sub, personapi.ErrSubscriptionExpired
62 }
63 return sub, nil
64}
65func (s *Store) project(tx *gorm.DB, sub Subscription) (NotificationSubscription, error) {
66 history, err := historyAt(tx, sub.TeamID, sub.Person)
67 if err != nil {
68 return NotificationSubscription{}, err
69 }
70 c, err := s.codec().Seal(scope(sub.TeamID, sub.Person), position{Subscription: sub.ID, After: sub.AckSequence, History: history})
71 return NotificationSubscription{ID: sub.ID, DeviceID: sub.DeviceID, Cursor: c, Revision: sub.Revision, Active: sub.Active, ExpiresAt: sub.ExpiresAt}, err
72}
73func (s *Store) SubscribeNotifications(ctx context.Context, a kernel.Actor, device string, m kernel.Mutation) (out NotificationSubscription, err error) {
74 if !m.Valid() || device == "" || len(device) > 128 {
75 return out, s.Invalid
76 }
77 ctx, err = personapi.ApplicationRequest(ctx, a, "notifications.subscribe", device, struct {
78 Device string
79 Revision int64
80 }{device, m.Revision}, m)
81 if err != nil {
82 return
83 }
84 err = s.Write(ctx, func(tx *gorm.DB) error {
85 team, e := s.authorize(tx, ctx, a)
86 if e != nil {
87 return e
88 }
89 expiry, e := s.device(tx, ctx, a, device)
90 if e != nil {
91 return e
92 }
93 if replay, e := personapi.Replay(tx, ctx, &out, s.Conflict); e != nil || replay {
94 if e != nil {
95 return e
96 }
97 _, e = s.subscription(tx, ctx, a, team, out.ID, true)
98 return e
99 }
100 now := s.Now().UTC()
101 if max := now.Add(30 * 24 * time.Hour); expiry.After(max) {
102 expiry = max
103 }
104 // One active subscription per device; only an explicit action replaces it.
105 if e = tx.Model(&Subscription{}).Where("team_id=? AND person=? AND device_id=? AND active=?", team, a.Address, device, true).Select("active", "revision").Updates(map[string]any{"active": false, "revision": gorm.Expr("revision+1")}).Error; e != nil {
106 return e
107 }
108 sub := Subscription{ID: rand.Text(), TeamID: team, Person: a.Address, DeviceID: device, Revision: 1, Active: true, CreatedAt: now, ExpiresAt: expiry}
109 if e = tx.Create(&sub).Error; e != nil {
110 return e
111 }
112 out, e = s.project(tx, sub)
113 if e != nil {
114 return e
115 }
116 if e = s.Audit(tx, a, "notifications.subscribe", sub.ID); e != nil {
117 return e
118 }
119 return personapi.SaveResult(tx, ctx, out, s.Conflict)
120 })
121 return
122}
123func (s *Store) NotificationSubscription(ctx context.Context, a kernel.Actor, id string) (out NotificationSubscription, err error) {
124 err = s.Read(ctx, func(tx *gorm.DB) error {
125 team, e := s.authorize(tx, ctx, a)
126 if e != nil {
127 return e
128 }
129 sub, e := s.subscription(tx, ctx, a, team, id, false)
130 if e != nil {
131 return e
132 }
133 out, e = s.project(tx, sub)
134 return e
135 })
136 return
137}
138func (s *Store) UnsubscribeNotifications(ctx context.Context, a kernel.Actor, id string, m kernel.Mutation) error {
139 return s.change(ctx, a, id, "", m)
140}
141func (s *Store) AcknowledgeNotification(ctx context.Context, a kernel.Actor, id, notification string, m kernel.Mutation) error {
142 if notification == "" || len(notification) > 128 {
143 return s.Invalid
144 }
145 return s.change(ctx, a, id, notification, m)
146}
147func (s *Store) change(ctx context.Context, a kernel.Actor, id, notification string, m kernel.Mutation) error {
148 if !m.Valid() {
149 return s.Invalid
150 }
151 op := "notifications.unsubscribe"
152 if notification != "" {
153 op = "notifications.ack"
154 }
155 ctx, err := personapi.ApplicationRequest(ctx, a, op, id, struct {
156 ID string
157 Revision int64
158 }{notification, m.Revision}, m)
159 if err != nil {
160 return err
161 }
162 return s.Write(ctx, func(tx *gorm.DB) error {
163 team, e := s.authorize(tx, ctx, a)
164 if e != nil {
165 return e
166 }
167 sub, e := s.subscription(tx, ctx, a, team, id, notification != "")
168 if e != nil {
169 return e
170 }
171 var ack personapi.Ack
172 if replay, e := personapi.Replay(tx, ctx, &ack, s.Conflict); e != nil || replay {
173 return e
174 }
175 if sub.Revision != m.Revision {
176 return s.Conflict
177 }
178 if notification == "" {
179 sub.Active = false
180 } else {
181 var n Event
182 if e = tx.Where("id=? AND team_id=? AND recipient=?", notification, team, a.Address).Take(&n).Error; e != nil {
183 if errors.Is(e, gorm.ErrRecordNotFound) {
184 return s.NotFound
185 }
186 return e
187 }
188 var d Delivery
189 if e = tx.Where("subscription_id=? AND sequence=?", id, n.Sequence).Take(&d).Error; e != nil {
190 if errors.Is(e, gorm.ErrRecordNotFound) {
191 return s.NotFound
192 }
193 return e
194 }
195 now := s.Now().UTC()
196 if d.AcknowledgedAt == nil {
197 if e = tx.Model(&Delivery{}).Where("subscription_id=? AND sequence=?", id, n.Sequence).Select("acknowledged_at").Update("acknowledged_at", now).Error; e != nil {
198 return e
199 }
200 }
201 // Every recipient event counts, including ones this device has not fetched.
202 // Numeric gaps belonging to other recipients do not block this cursor.
203 var first struct{ Sequence int64 }
204 if e = tx.Table("notification_outbox n").Select("n.sequence").Joins("LEFT JOIN notification_deliveries d ON d.sequence=n.sequence AND d.subscription_id=?", id).Where("n.team_id=? AND n.recipient=? AND n.sequence>? AND d.acknowledged_at IS NULL", team, a.Address, sub.AckSequence).Order("n.sequence").Limit(1).Scan(&first).Error; e != nil {
205 return e
206 }
207 q := tx.Model(&Event{}).Where("team_id=? AND recipient=?", team, a.Address)
208 if first.Sequence > 0 {
209 q = q.Where("sequence<?", first.Sequence)
210 }
211 var through int64
212 if e = q.Select("COALESCE(MAX(sequence),0)").Scan(&through).Error; e != nil {
213 return e
214 }
215 if through > sub.AckSequence {
216 sub.AckSequence = through
217 }
218 // Retention begins once someone acknowledges. Other devices keep their own unread state.
219 if e = tx.Model(&Event{}).Where("id=? AND acknowledged_at IS NULL", n.ID).Select("acknowledged_at").Update("acknowledged_at", now).Error; e != nil {
220 return e
221 }
222 }
223 sub.Revision++
224 updated := tx.Model(&Subscription{}).Where("id=? AND revision=?", id, m.Revision).Select("active", "ack_sequence", "revision").Updates(&sub)
225 if updated.Error != nil {
226 return updated.Error
227 }
228 if updated.RowsAffected != 1 {
229 return s.Conflict
230 }
231 if e = s.Audit(tx, a, op, id); e != nil {
232 return e
233 }
234 return personapi.SaveResult(tx, ctx, personapi.Ack{Revision: sub.Revision}, s.Conflict)
235 })
236}
237func (s *Store) Notifications(ctx context.Context, a kernel.Actor, cursor string, limit int) (out personapi.Page[Notification], err error) {
238 out.Items = []Notification{}
239 if limit == 0 {
240 limit = 50
241 }
242 if limit < 1 || limit > 100 {
243 return out, s.Invalid
244 }
245 err = s.Write(personapi.WithoutRequest(ctx), func(tx *gorm.DB) error {
246 team, e := s.authorize(tx, ctx, a)
247 if e != nil {
248 return e
249 }
250 var pos position
251 if cursor != "" && s.codec().Open(scope(team, a.Address), cursor, &pos) != nil {
252 return s.CursorExpired
253 }
254 if pos.After < 0 {
255 return s.CursorExpired
256 }
257 if pos.Subscription != "" {
258 if _, e = s.subscription(tx, ctx, a, team, pos.Subscription, true); e != nil {
259 return e
260 }
261 }
262 if e = s.prune(tx, team, a.Address); e != nil {
263 return e
264 }
265 var history History
266 e = tx.Where("team_id=? AND person=?", team, a.Address).Take(&history).Error
267 if e != nil && !errors.Is(e, gorm.ErrRecordNotFound) {
268 return e
269 }
270 if cursor != "" && pos.History < history.PrunedThrough {
271 return s.CursorExpired
272 }
273 pos.History = history.PrunedThrough
274 var rows []Event
275 if e = tx.Where("team_id=? AND recipient=? AND sequence>?", team, a.Address, pos.After).Order("sequence").Limit(limit).Find(&rows).Error; e != nil {
276 return e
277 }
278 for _, row := range rows {
279 n := Notification{ID: row.ID, Kind: row.Kind, ResourceID: row.ResourceID, DeepLink: row.DeepLink, ResourceRevision: row.ResourceRevision, CreatedAt: row.CreatedAt.UTC(), State: row.State}
280 current, e := s.current(tx, row)
281 if e != nil {
282 return e
283 }
284 if !current {
285 if row.State != "superseded" {
286 if e = tx.Model(&Event{}).Where("sequence=?", row.Sequence).Select("state").Update("state", "superseded").Error; e != nil {
287 return e
288 }
289 }
290 n.State = "superseded"
291 }
292 if pos.Subscription != "" {
293 d := Delivery{SubscriptionID: pos.Subscription, Sequence: row.Sequence, DeliveredAt: s.Now().UTC()}
294 if e = tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&d).Error; e != nil {
295 return e
296 }
297 if e = tx.Where("subscription_id=? AND sequence=?", pos.Subscription, row.Sequence).Take(&d).Error; e != nil {
298 return e
299 }
300 if d.AcknowledgedAt != nil && n.State != "superseded" {
301 n.State = "acknowledged"
302 }
303 }
304 out.Items = append(out.Items, n)
305 pos.After = row.Sequence
306 }
307 out.NextCursor, e = s.codec().Seal(scope(team, a.Address), pos)
308 if e != nil {
309 return e
310 }
311 out.Revision = personapi.Revision(out.Items)
312 return nil
313 })
314 return
315}
316func (s *Store) AllowNotificationSubscription(ctx context.Context, a kernel.Actor, id string) bool {
317 allowed := false
318 err := s.Read(ctx, func(tx *gorm.DB) error {
319 team, e := s.authorize(tx, ctx, a)
320 if e != nil {
321 return e
322 }
323 _, e = s.subscription(tx, ctx, a, team, id, true)
324 allowed = e == nil
325 return e
326 })
327 return err == nil && allowed
328}
329
330func (s *Store) authorize(tx *gorm.DB, ctx context.Context, a kernel.Actor) (string, error) {
331 team, err := s.Authorize(tx, a)
332 if err != nil {
333 return "", err
334 }
335 if p, ok := personapi.PrincipalFrom(ctx); ok {
336 if p.Address != a.Address {
337 return "", s.Forbidden
338 }
339 var epoch int64
340 if err = tx.Table("members").Select("session_epoch").Where("address=? AND active=1", a.Address).Scan(&epoch).Error; err != nil {
341 return "", err
342 }
343 if p.SessionEpoch < epoch {
344 return "", s.Forbidden
345 }
346 if p.CredentialID != "" {
347 if _, err = s.Devices().VerifyAt(tx, p.CredentialID, ""); err != nil {
348 return "", err
349 }
350 }
351 }
352 return team, nil
353}
354