Debian Codegraph @

message/cache.go

raw
1 package message
2
3 import (
4 "database/sql"
5 "encoding/json"
6 "errors"
7 "net/netip"
8 "strings"
9 "sync"
10 "time"
11
12 "heckel.io/ntfy/v2/db"
13 "heckel.io/ntfy/v2/log"
14 "heckel.io/ntfy/v2/model"
15 "heckel.io/ntfy/v2/util"
16 )
17
18 const (
19 tagMessageCache = "message_cache"
20 schemaStore = "message" // Store name in the schema_version table (see db/schema)
21 )
22
23 var errNoRows = errors.New("no rows found")
24
25 // queries holds the database-specific SQL queries
26 type queries struct {
27 insertMessage string
28 selectScheduledMessageIDsBySeqID string
29 deleteScheduledBySequenceID string
30 updateMessagesForTopicExpiry string
31 selectMessagesByID string
32 selectMessagesSinceTime string
33 selectMessagesSinceTimeScheduled string
34 selectMessagesSinceID string
35 selectMessagesSinceIDScheduled string
36 selectMessagesLatest string
37 selectMessagesDue string
38 deleteExpiredMessages string
39 updateMessagePublished string
40 selectMessagesCount string
41 selectTopics string
42 markExpiredAttachmentsDeleted string
43 selectAttachmentsSizeBySender string
44 selectAttachmentsSizeByUserID string
45 selectAttachmentsWithSizes string
46 selectStats string
47 updateStats string
48 updateMessageTime string
49 }
50
51 // Cache stores published messages
52 type Cache struct {
53 db *db.DB
54 queue *util.BatchingQueue[*model.Message]
55 nop bool
56 mu *sync.Mutex // nil for PostgreSQL (concurrent writes supported), set for SQLite (single writer)
57 queries queries
58 }
59
60 func newCache(db *db.DB, queries queries, mu *sync.Mutex, batchSize int, batchTimeout time.Duration, nop bool) *Cache {
61 var queue *util.BatchingQueue[*model.Message]
62 if batchSize > 0 || batchTimeout > 0 {
63 queue = util.NewBatchingQueue[*model.Message](batchSize, batchTimeout)
64 }
65 c := &Cache{
66 db: db,
67 queue: queue,
68 nop: nop,
69 mu: mu,
70 queries: queries,
71 }
72 go c.processMessageBatches()
73 return c
74 }
75
76 func (c *Cache) maybeLock() {
77 if c.mu != nil {
78 c.mu.Lock()
79 }
80 }
81
82 func (c *Cache) maybeUnlock() {
83 if c.mu != nil {
84 c.mu.Unlock()
85 }
86 }
87
88 // AddMessage stores a message to the message cache synchronously, or queues it to be stored at a later date asynchronously.
89 // The message is queued only if "batchSize" or "batchTimeout" are passed to the constructor.
90 func (c *Cache) AddMessage(m *model.Message) error {
91 if c.queue != nil {
92 c.queue.Enqueue(m)
93 return nil
94 }
95 return c.addMessages([]*model.Message{m})
96 }
97
98 // AddMessages synchronously stores a batch of messages to the message cache
99 func (c *Cache) AddMessages(ms []*model.Message) error {
100 return c.addMessages(ms)
101 }
102
103 func (c *Cache) addMessages(ms []*model.Message) error {
104 c.maybeLock()
105 defer c.maybeUnlock()
106 if c.nop {
107 return nil
108 }
109 if len(ms) == 0 {
110 return nil
111 }
112 start := time.Now()
113 tx, err := c.db.Begin()
114 if err != nil {
115 return err
116 }
117 defer tx.Rollback()
118 stmt, err := tx.Prepare(c.queries.insertMessage)
119 if err != nil {
120 return err
121 }
122 defer stmt.Close()
123 for _, m := range ms {
124 if m.Event != model.MessageEvent && m.Event != model.MessageDeleteEvent && m.Event != model.MessageClearEvent {
125 return model.ErrUnexpectedMessageType
126 }
127 published := m.Time <= time.Now().Unix()
128 tags := util.SanitizeUTF8(strings.Join(m.Tags, ","))
129 var attachmentName, attachmentType, attachmentURL string
130 var attachmentSize, attachmentExpires int64
131 var attachmentDeleted bool
132 if m.Attachment != nil {
133 attachmentName = util.SanitizeUTF8(m.Attachment.Name)
134 attachmentType = util.SanitizeUTF8(m.Attachment.Type)
135 attachmentSize = m.Attachment.Size
136 attachmentExpires = m.Attachment.Expires
137 attachmentURL = util.SanitizeUTF8(m.Attachment.URL)
138 }
139 var actionsStr string
140 if len(m.Actions) > 0 {
141 actionsBytes, err := json.Marshal(m.Actions)
142 if err != nil {
143 return err
144 }
145 actionsStr = string(actionsBytes)
146 }
147 var sender string
148 if m.Sender.IsValid() {
149 sender = m.Sender.String()
150 }
151 _, err := stmt.Exec(
152 m.ID,
153 m.SequenceID,
154 m.Time,
155 m.Event,
156 m.Expires,
157 util.SanitizeUTF8(m.Topic),
158 util.SanitizeUTF8(m.Message),
159 util.SanitizeUTF8(m.Title),
160 m.Priority,
161 tags,
162 util.SanitizeUTF8(m.Click),
163 util.SanitizeUTF8(m.Icon),
164 actionsStr,
165 attachmentName,
166 attachmentType,
167 attachmentSize,
168 attachmentExpires,
169 attachmentURL,
170 attachmentDeleted, // Always zero
171 sender,
172 m.User,
173 util.SanitizeUTF8(m.ContentType),
174 m.Encoding,
175 published,
176 )
177 if err != nil {
178 return err
179 }
180 }
181 if err := tx.Commit(); err != nil {
182 log.Tag(tagMessageCache).Err(err).Error("Writing %d message(s) failed (took %v)", len(ms), time.Since(start))
183 return err
184 }
185 log.Tag(tagMessageCache).Debug("Wrote %d message(s) in %v", len(ms), time.Since(start))
186 return nil
187 }
188
189 // Messages returns messages for a topic since the given marker, optionally including scheduled messages
190 func (c *Cache) Messages(topic string, since model.SinceMarker, scheduled bool) ([]*model.Message, error) {
191 if since.IsNone() {
192 return make([]*model.Message, 0), nil
193 } else if since.IsLatest() {
194 return c.messagesLatest(topic)
195 } else if since.IsID() {
196 return c.messagesSinceID(topic, since, scheduled)
197 }
198 return c.messagesSinceTime(topic, since, scheduled)
199 }
200
201 func (c *Cache) messagesSinceTime(topic string, since model.SinceMarker, scheduled bool) ([]*model.Message, error) {
202 var rows *sql.Rows
203 var err error
204 rdb := c.db.ReadOnly()
205 if scheduled {
206 rows, err = rdb.Query(c.queries.selectMessagesSinceTimeScheduled, topic, since.Time().Unix())
207 } else {
208 rows, err = rdb.Query(c.queries.selectMessagesSinceTime, topic, since.Time().Unix())
209 }
210 if err != nil {
211 return nil, err
212 }
213 return readMessages(rows)
214 }
215
216 func (c *Cache) messagesSinceID(topic string, since model.SinceMarker, scheduled bool) ([]*model.Message, error) {
217 var rows *sql.Rows
218 var err error
219 rdb := c.db.ReadOnly()
220 if scheduled {
221 rows, err = rdb.Query(c.queries.selectMessagesSinceIDScheduled, topic, since.ID())
222 } else {
223 rows, err = rdb.Query(c.queries.selectMessagesSinceID, topic, since.ID())
224 }
225 if err != nil {
226 return nil, err
227 }
228 return readMessages(rows)
229 }
230
231 func (c *Cache) messagesLatest(topic string) ([]*model.Message, error) {
232 rows, err := c.db.ReadOnly().Query(c.queries.selectMessagesLatest, topic)
233 if err != nil {
234 return nil, err
235 }
236 return readMessages(rows)
237 }
238
239 // MessagesDue returns all messages that are due for publishing
240 func (c *Cache) MessagesDue() ([]*model.Message, error) {
241 rows, err := c.db.Query(c.queries.selectMessagesDue, time.Now().Unix())
242 if err != nil {
243 return nil, err
244 }
245 return readMessages(rows)
246 }
247
248 // DeleteExpiredMessages deletes up to `limit` expired messages in a single query
249 // and returns the number of deleted rows.
250 func (c *Cache) DeleteExpiredMessages(limit int) (int64, error) {
251 c.maybeLock()
252 defer c.maybeUnlock()
253 result, err := c.db.Exec(c.queries.deleteExpiredMessages, time.Now().Unix(), limit)
254 if err != nil {
255 return 0, err
256 }
257 return result.RowsAffected()
258 }
259
260 // Message returns the message with the given ID, or ErrMessageNotFound if not found
261 func (c *Cache) Message(id string) (*model.Message, error) {
262 rows, err := c.db.ReadOnly().Query(c.queries.selectMessagesByID, id)
263 if err != nil {
264 return nil, err
265 }
266 defer rows.Close()
267 if !rows.Next() {
268 return nil, model.ErrMessageNotFound
269 }
270 return readMessage(rows)
271 }
272
273 // UpdateMessageTime updates the time column for a message by ID. This is only used for testing.
274 func (c *Cache) UpdateMessageTime(messageID string, timestamp int64) error {
275 c.maybeLock()
276 defer c.maybeUnlock()
277 _, err := c.db.Exec(c.queries.updateMessageTime, timestamp, messageID)
278 return err
279 }
280
281 // MarkPublished marks a message as published
282 func (c *Cache) MarkPublished(m *model.Message) error {
283 c.maybeLock()
284 defer c.maybeUnlock()
285 _, err := c.db.Exec(c.queries.updateMessagePublished, m.ID)
286 return err
287 }
288
289 // MessagesCount returns the total number of messages in the cache
290 func (c *Cache) MessagesCount() (int, error) {
291 rows, err := c.db.ReadOnly().Query(c.queries.selectMessagesCount)
292 if err != nil {
293 return 0, err
294 }
295 defer rows.Close()
296 if !rows.Next() {
297 return 0, errNoRows
298 }
299 var count int
300 if err := rows.Scan(&count); err != nil {
301 return 0, err
302 }
303 return count, nil
304 }
305
306 // Topics returns a list of all topics with messages in the cache
307 func (c *Cache) Topics() ([]string, error) {
308 rows, err := c.db.ReadOnly().Query(c.queries.selectTopics)
309 if err != nil {
310 return nil, err
311 }
312 defer rows.Close()
313 return readStrings(rows)
314 }
315
316 // DeleteScheduledBySequenceID deletes unpublished (scheduled) messages with the given topic and sequence ID.
317 // It returns the message IDs of the deleted messages, which can be used to clean up attachment files.
318 func (c *Cache) DeleteScheduledBySequenceID(topic, sequenceID string) ([]string, error) {
319 c.maybeLock()
320 defer c.maybeUnlock()
321 return db.QueryTx(c.db, func(tx *sql.Tx) ([]string, error) {
322 rows, err := tx.Query(c.queries.selectScheduledMessageIDsBySeqID, topic, sequenceID)
323 if err != nil {
324 return nil, err
325 }
326 defer rows.Close()
327 ids, err := readStrings(rows)
328 if err != nil {
329 return nil, err
330 }
331 rows.Close() // Close rows before executing delete in same transaction
332 if _, err := tx.Exec(c.queries.deleteScheduledBySequenceID, topic, sequenceID); err != nil {
333 return nil, err
334 }
335 return ids, nil
336 })
337 }
338
339 // ExpireMessages marks messages in the given topics as expired
340 func (c *Cache) ExpireMessages(topics ...string) error {
341 c.maybeLock()
342 defer c.maybeUnlock()
343 return db.ExecTx(c.db, func(tx *sql.Tx) error {
344 for _, t := range topics {
345 if _, err := tx.Exec(c.queries.updateMessagesForTopicExpiry, time.Now().Unix()-1, t); err != nil {
346 return err
347 }
348 }
349 return nil
350 })
351 }
352
353 // MarkExpiredAttachmentsDeleted marks up to `limit` expired attachments as deleted in a single
354 // query and returns the number of updated rows.
355 func (c *Cache) MarkExpiredAttachmentsDeleted(limit int) (int64, error) {
356 c.maybeLock()
357 defer c.maybeUnlock()
358 result, err := c.db.Exec(c.queries.markExpiredAttachmentsDeleted, time.Now().Unix(), limit)
359 if err != nil {
360 return 0, err
361 }
362 return result.RowsAffected()
363 }
364
365 // AttachmentBytesUsedBySender returns the total size of active attachments sent by the given sender
366 func (c *Cache) AttachmentBytesUsedBySender(sender string) (int64, error) {
367 rows, err := c.db.ReadOnly().Query(c.queries.selectAttachmentsSizeBySender, sender, time.Now().Unix())
368 if err != nil {
369 return 0, err
370 }
371 return c.readAttachmentBytesUsed(rows)
372 }
373
374 // AttachmentBytesUsedByUser returns the total size of active attachments for the given user
375 func (c *Cache) AttachmentBytesUsedByUser(userID string) (int64, error) {
376 rows, err := c.db.ReadOnly().Query(c.queries.selectAttachmentsSizeByUserID, userID, time.Now().Unix())
377 if err != nil {
378 return 0, err
379 }
380 return c.readAttachmentBytesUsed(rows)
381 }
382
383 // AttachmentsWithSizes returns a map of message ID to attachment size for all active
384 // (non-expired, non-deleted) attachments. This is used to hydrate the attachment store's
385 // size tracking on startup and during periodic sync.
386 func (c *Cache) AttachmentsWithSizes() (map[string]int64, error) {
387 rows, err := c.db.ReadOnly().Query(c.queries.selectAttachmentsWithSizes, time.Now().Unix())
388 if err != nil {
389 return nil, err
390 }
391 defer rows.Close()
392 attachments := make(map[string]int64)
393 for rows.Next() {
394 var id string
395 var size int64
396 if err := rows.Scan(&id, &size); err != nil {
397 return nil, err
398 }
399 attachments[id] = size
400 }
401 if err := rows.Err(); err != nil {
402 return nil, err
403 }
404 return attachments, nil
405 }
406
407 func (c *Cache) readAttachmentBytesUsed(rows *sql.Rows) (int64, error) {
408 defer rows.Close()
409 var size int64
410 if !rows.Next() {
411 return 0, errors.New("no rows found")
412 }
413 if err := rows.Scan(&size); err != nil {
414 return 0, err
415 } else if err := rows.Err(); err != nil {
416 return 0, err
417 }
418 return size, nil
419 }
420
421 // UpdateStats updates the total message count statistic
422 func (c *Cache) UpdateStats(messages int64) error {
423 c.maybeLock()
424 defer c.maybeUnlock()
425 _, err := c.db.Exec(c.queries.updateStats, messages)
426 return err
427 }
428
429 // Stats returns the total message count statistic
430 func (c *Cache) Stats() (messages int64, err error) {
431 rows, err := c.db.ReadOnly().Query(c.queries.selectStats)
432 if err != nil {
433 return 0, err
434 }
435 defer rows.Close()
436 if !rows.Next() {
437 return 0, errNoRows
438 }
439 if err := rows.Scan(&messages); err != nil {
440 return 0, err
441 }
442 return messages, nil
443 }
444
445 // Close closes the underlying database connection
446 func (c *Cache) Close() error {
447 return c.db.Close()
448 }
449
450 func (c *Cache) processMessageBatches() {
451 if c.queue == nil {
452 return
453 }
454 for messages := range c.queue.Dequeue() {
455 if err := c.addMessages(messages); err != nil {
456 log.Tag(tagMessageCache).Err(err).Error("Cannot write message batch")
457 }
458 }
459 }
460
461 func readMessages(rows *sql.Rows) ([]*model.Message, error) {
462 defer rows.Close()
463 messages := make([]*model.Message, 0)
464 for rows.Next() {
465 m, err := readMessage(rows)
466 if err != nil {
467 return nil, err
468 }
469 messages = append(messages, m)
470 }
471 if err := rows.Err(); err != nil {
472 return nil, err
473 }
474 return messages, nil
475 }
476
477 func readMessage(rows *sql.Rows) (*model.Message, error) {
478 var timestamp, expires, attachmentSize, attachmentExpires int64
479 var priority int
480 var id, sequenceID, event, topic, msg, title, tagsStr, click, icon, actionsStr, attachmentName, attachmentType, attachmentURL, sender, user, contentType, encoding string
481 err := rows.Scan(
482 &id,
483 &sequenceID,
484 &timestamp,
485 &event,
486 &expires,
487 &topic,
488 &msg,
489 &title,
490 &priority,
491 &tagsStr,
492 &click,
493 &icon,
494 &actionsStr,
495 &attachmentName,
496 &attachmentType,
497 &attachmentSize,
498 &attachmentExpires,
499 &attachmentURL,
500 &sender,
501 &user,
502 &contentType,
503 &encoding,
504 )
505 if err != nil {
506 return nil, err
507 }
508 var tags []string
509 if tagsStr != "" {
510 tags = strings.Split(tagsStr, ",")
511 }
512 var actions []*model.Action
513 if actionsStr != "" {
514 if err := json.Unmarshal([]byte(actionsStr), &actions); err != nil {
515 return nil, err
516 }
517 }
518 senderIP, err := netip.ParseAddr(sender)
519 if err != nil {
520 senderIP = netip.Addr{} // if no IP stored in database, return invalid address
521 }
522 var att *model.Attachment
523 if attachmentName != "" && attachmentURL != "" {
524 att = &model.Attachment{
525 Name: attachmentName,
526 Type: attachmentType,
527 Size: attachmentSize,
528 Expires: attachmentExpires,
529 URL: attachmentURL,
530 }
531 }
532 return &model.Message{
533 ID: id,
534 SequenceID: sequenceID,
535 Time: timestamp,
536 Expires: expires,
537 Event: event,
538 Topic: topic,
539 Message: msg,
540 Title: title,
541 Priority: priority,
542 Tags: tags,
543 Click: click,
544 Icon: icon,
545 Actions: actions,
546 Attachment: att,
547 Sender: senderIP,
548 User: user,
549 ContentType: contentType,
550 Encoding: encoding,
551 }, nil
552 }
553
554 func readStrings(rows *sql.Rows) ([]string, error) {
555 strs := make([]string, 0)
556 for rows.Next() {
557 var s string
558 if err := rows.Scan(&s); err != nil {
559 return nil, err
560 }
561 strs = append(strs, s)
562 }
563 if err := rows.Err(); err != nil {
564 return nil, err
565 }
566 return strs, nil
567 }