backfillqueue.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan, Sumner Evans
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package database
  17. import (
  18. "database/sql"
  19. "errors"
  20. "fmt"
  21. "time"
  22. log "maunium.net/go/maulogger/v2"
  23. "maunium.net/go/mautrix/id"
  24. )
  25. type BackfillType int
  26. const (
  27. BackfillImmediate BackfillType = 0
  28. BackfillForward BackfillType = 100
  29. BackfillDeferred BackfillType = 200
  30. BackfillMedia BackfillType = 300
  31. )
  32. func (bt BackfillType) String() string {
  33. switch bt {
  34. case BackfillImmediate:
  35. return "IMMEDIATE"
  36. case BackfillForward:
  37. return "FORWARD"
  38. case BackfillDeferred:
  39. return "DEFERRED"
  40. case BackfillMedia:
  41. return "MEDIA"
  42. }
  43. return "UNKNOWN"
  44. }
  45. type BackfillQuery struct {
  46. db *Database
  47. log log.Logger
  48. }
  49. func (bq *BackfillQuery) New() *Backfill {
  50. return &Backfill{
  51. db: bq.db,
  52. log: bq.log,
  53. Portal: &PortalKey{},
  54. }
  55. }
  56. func (bq *BackfillQuery) NewWithValues(userID id.UserID, backfillType BackfillType, priority int, portal *PortalKey, timeStart *time.Time, timeEnd *time.Time, maxBatchEvents, maxTotalEvents, batchDelay int) *Backfill {
  57. return &Backfill{
  58. db: bq.db,
  59. log: bq.log,
  60. UserID: userID,
  61. BackfillType: backfillType,
  62. Priority: priority,
  63. Portal: portal,
  64. TimeStart: timeStart,
  65. TimeEnd: timeEnd,
  66. MaxBatchEvents: maxBatchEvents,
  67. MaxTotalEvents: maxTotalEvents,
  68. BatchDelay: batchDelay,
  69. }
  70. }
  71. const (
  72. getNextBackfillQuery = `
  73. SELECT queue_id, user_mxid, type, priority, portal_jid, portal_receiver, time_start, time_end, max_batch_events, max_total_events, batch_delay
  74. FROM backfill_queue
  75. WHERE user_mxid=$1
  76. AND completed_at IS NULL
  77. ORDER BY type, priority, queue_id
  78. LIMIT 1
  79. `
  80. )
  81. // GetNext returns the next backfill to perform
  82. func (bq *BackfillQuery) GetNext(userID id.UserID) (backfill *Backfill) {
  83. rows, err := bq.db.Query(getNextBackfillQuery, userID)
  84. defer rows.Close()
  85. if err != nil || rows == nil {
  86. bq.log.Error(err)
  87. return
  88. }
  89. if rows.Next() {
  90. backfill = bq.New().Scan(rows)
  91. }
  92. return
  93. }
  94. func (bq *BackfillQuery) DeleteAll(userID id.UserID) error {
  95. _, err := bq.db.Exec("DELETE FROM backfill_queue WHERE user_mxid=$1", userID)
  96. return err
  97. }
  98. func (bq *BackfillQuery) DeleteAllForPortal(userID id.UserID, portalKey PortalKey) error {
  99. _, err := bq.db.Exec(`
  100. DELETE FROM backfill_queue
  101. WHERE user_mxid=$1
  102. AND portal_jid=$2
  103. AND portal_receiver=$3
  104. `, userID, portalKey.JID, portalKey.Receiver)
  105. return err
  106. }
  107. type Backfill struct {
  108. db *Database
  109. log log.Logger
  110. // Fields
  111. QueueID int
  112. UserID id.UserID
  113. BackfillType BackfillType
  114. Priority int
  115. Portal *PortalKey
  116. TimeStart *time.Time
  117. TimeEnd *time.Time
  118. MaxBatchEvents int
  119. MaxTotalEvents int
  120. BatchDelay int
  121. CompletedAt *time.Time
  122. }
  123. func (b *Backfill) String() string {
  124. return fmt.Sprintf("Backfill{QueueID: %d, UserID: %s, BackfillType: %s, Priority: %d, Portal: %s, TimeStart: %s, TimeEnd: %s, MaxBatchEvents: %d, MaxTotalEvents: %d, BatchDelay: %d, CompletedAt: %s}",
  125. b.QueueID, b.UserID, b.BackfillType, b.Priority, b.Portal, b.TimeStart, b.TimeEnd, b.MaxBatchEvents, b.MaxTotalEvents, b.BatchDelay, b.CompletedAt,
  126. )
  127. }
  128. func (b *Backfill) Scan(row Scannable) *Backfill {
  129. err := row.Scan(&b.QueueID, &b.UserID, &b.BackfillType, &b.Priority, &b.Portal.JID, &b.Portal.Receiver, &b.TimeStart, &b.TimeEnd, &b.MaxBatchEvents, &b.MaxTotalEvents, &b.BatchDelay)
  130. if err != nil {
  131. if !errors.Is(err, sql.ErrNoRows) {
  132. b.log.Errorln("Database scan failed:", err)
  133. }
  134. return nil
  135. }
  136. return b
  137. }
  138. func (b *Backfill) Insert() {
  139. rows, err := b.db.Query(`
  140. INSERT INTO backfill_queue
  141. (user_mxid, type, priority, portal_jid, portal_receiver, time_start, time_end, max_batch_events, max_total_events, batch_delay, completed_at)
  142. VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
  143. RETURNING queue_id
  144. `, b.UserID, b.BackfillType, b.Priority, b.Portal.JID, b.Portal.Receiver, b.TimeStart, b.TimeEnd, b.MaxBatchEvents, b.MaxTotalEvents, b.BatchDelay, b.CompletedAt)
  145. defer rows.Close()
  146. if err != nil || !rows.Next() {
  147. b.log.Warnfln("Failed to insert %v/%s with priority %d: %v", b.BackfillType, b.Portal.JID, b.Priority, err)
  148. return
  149. }
  150. err = rows.Scan(&b.QueueID)
  151. if err != nil {
  152. b.log.Warnfln("Failed to insert %s/%s with priority %s: %v", b.BackfillType, b.Portal.JID, b.Priority, err)
  153. }
  154. }
  155. func (b *Backfill) MarkDone() {
  156. if b.QueueID == 0 {
  157. b.log.Errorf("Cannot delete backfill without queue_id. Maybe it wasn't actually inserted in the database?")
  158. return
  159. }
  160. _, err := b.db.Exec("UPDATE backfill_queue SET completed_at=$1 WHERE queue_id=$2", time.Now(), b.QueueID)
  161. if err != nil {
  162. b.log.Warnfln("Failed to mark %s/%s as complete: %v", b.BackfillType, b.Priority, err)
  163. }
  164. }