backfillqueue.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. "strconv"
  22. "strings"
  23. "time"
  24. log "maunium.net/go/maulogger/v2"
  25. "maunium.net/go/mautrix/id"
  26. )
  27. type BackfillType int
  28. const (
  29. BackfillImmediate BackfillType = 0
  30. BackfillForward BackfillType = 100
  31. BackfillDeferred BackfillType = 200
  32. )
  33. func (bt BackfillType) String() string {
  34. switch bt {
  35. case BackfillImmediate:
  36. return "IMMEDIATE"
  37. case BackfillForward:
  38. return "FORWARD"
  39. case BackfillDeferred:
  40. return "DEFERRED"
  41. }
  42. return "UNKNOWN"
  43. }
  44. type BackfillQuery struct {
  45. db *Database
  46. log log.Logger
  47. }
  48. func (bq *BackfillQuery) New() *Backfill {
  49. return &Backfill{
  50. db: bq.db,
  51. log: bq.log,
  52. Portal: &PortalKey{},
  53. }
  54. }
  55. func (bq *BackfillQuery) NewWithValues(userID id.UserID, backfillType BackfillType, priority int, portal *PortalKey, timeStart *time.Time, maxBatchEvents, maxTotalEvents, batchDelay int) *Backfill {
  56. return &Backfill{
  57. db: bq.db,
  58. log: bq.log,
  59. UserID: userID,
  60. BackfillType: backfillType,
  61. Priority: priority,
  62. Portal: portal,
  63. TimeStart: timeStart,
  64. MaxBatchEvents: maxBatchEvents,
  65. MaxTotalEvents: maxTotalEvents,
  66. BatchDelay: batchDelay,
  67. }
  68. }
  69. const (
  70. getNextBackfillQuery = `
  71. SELECT queue_id, user_mxid, type, priority, portal_jid, portal_receiver, time_start, max_batch_events, max_total_events, batch_delay
  72. FROM backfill_queue
  73. WHERE user_mxid=$1
  74. AND type IN (%s)
  75. AND (
  76. dispatch_time IS NULL
  77. OR (
  78. dispatch_time < current_timestamp - interval '15 minutes'
  79. AND completed_at IS NULL
  80. )
  81. )
  82. ORDER BY type, priority, queue_id
  83. LIMIT 1
  84. `
  85. )
  86. // GetNext returns the next backfill to perform
  87. func (bq *BackfillQuery) GetNext(userID id.UserID, backfillTypes []BackfillType) (backfill *Backfill) {
  88. types := []string{}
  89. for _, backfillType := range backfillTypes {
  90. types = append(types, strconv.Itoa(int(backfillType)))
  91. }
  92. rows, err := bq.db.Query(fmt.Sprintf(getNextBackfillQuery, strings.Join(types, ",")), userID)
  93. if err != nil || rows == nil {
  94. bq.log.Error(err)
  95. return
  96. }
  97. defer rows.Close()
  98. if rows.Next() {
  99. backfill = bq.New().Scan(rows)
  100. }
  101. return
  102. }
  103. func (bq *BackfillQuery) DeleteAll(userID id.UserID) {
  104. _, err := bq.db.Exec("DELETE FROM backfill_queue WHERE user_mxid=$1", userID)
  105. if err != nil {
  106. bq.log.Warnfln("Failed to delete backfill queue items for %s: %v", userID, err)
  107. }
  108. }
  109. func (bq *BackfillQuery) DeleteAllForPortal(userID id.UserID, portalKey PortalKey) {
  110. _, err := bq.db.Exec(`
  111. DELETE FROM backfill_queue
  112. WHERE user_mxid=$1
  113. AND portal_jid=$2
  114. AND portal_receiver=$3
  115. `, userID, portalKey.JID, portalKey.Receiver)
  116. if err != nil {
  117. bq.log.Warnfln("Failed to delete backfill queue items for %s/%s: %v", userID, portalKey.JID, err)
  118. }
  119. }
  120. type Backfill struct {
  121. db *Database
  122. log log.Logger
  123. // Fields
  124. QueueID int
  125. UserID id.UserID
  126. BackfillType BackfillType
  127. Priority int
  128. Portal *PortalKey
  129. TimeStart *time.Time
  130. MaxBatchEvents int
  131. MaxTotalEvents int
  132. BatchDelay int
  133. DispatchTime *time.Time
  134. CompletedAt *time.Time
  135. }
  136. func (b *Backfill) String() string {
  137. return fmt.Sprintf("Backfill{QueueID: %d, UserID: %s, BackfillType: %s, Priority: %d, Portal: %s, TimeStart: %s, MaxBatchEvents: %d, MaxTotalEvents: %d, BatchDelay: %d, DispatchTime: %s, CompletedAt: %s}",
  138. b.QueueID, b.UserID, b.BackfillType, b.Priority, b.Portal, b.TimeStart, b.MaxBatchEvents, b.MaxTotalEvents, b.BatchDelay, b.CompletedAt, b.DispatchTime,
  139. )
  140. }
  141. func (b *Backfill) Scan(row Scannable) *Backfill {
  142. err := row.Scan(&b.QueueID, &b.UserID, &b.BackfillType, &b.Priority, &b.Portal.JID, &b.Portal.Receiver, &b.TimeStart, &b.MaxBatchEvents, &b.MaxTotalEvents, &b.BatchDelay)
  143. if err != nil {
  144. if !errors.Is(err, sql.ErrNoRows) {
  145. b.log.Errorln("Database scan failed:", err)
  146. }
  147. return nil
  148. }
  149. return b
  150. }
  151. func (b *Backfill) Insert() {
  152. rows, err := b.db.Query(`
  153. INSERT INTO backfill_queue
  154. (user_mxid, type, priority, portal_jid, portal_receiver, time_start, max_batch_events, max_total_events, batch_delay, dispatch_time, completed_at)
  155. VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
  156. RETURNING queue_id
  157. `, b.UserID, b.BackfillType, b.Priority, b.Portal.JID, b.Portal.Receiver, b.TimeStart, b.MaxBatchEvents, b.MaxTotalEvents, b.BatchDelay, b.DispatchTime, b.CompletedAt)
  158. defer rows.Close()
  159. if err != nil || !rows.Next() {
  160. b.log.Warnfln("Failed to insert %v/%s with priority %d: %v", b.BackfillType, b.Portal.JID, b.Priority, err)
  161. return
  162. }
  163. err = rows.Scan(&b.QueueID)
  164. if err != nil {
  165. b.log.Warnfln("Failed to insert %s/%s with priority %s: %v", b.BackfillType, b.Portal.JID, b.Priority, err)
  166. }
  167. }
  168. func (b *Backfill) MarkDispatched() {
  169. if b.QueueID == 0 {
  170. b.log.Errorf("Cannot mark backfill as dispatched without queue_id. Maybe it wasn't actually inserted in the database?")
  171. return
  172. }
  173. _, err := b.db.Exec("UPDATE backfill_queue SET dispatch_time=$1 WHERE queue_id=$2", time.Now(), b.QueueID)
  174. if err != nil {
  175. b.log.Warnfln("Failed to mark %s/%s as dispatched: %v", b.BackfillType, b.Priority, err)
  176. }
  177. }
  178. func (b *Backfill) MarkDone() {
  179. if b.QueueID == 0 {
  180. b.log.Errorf("Cannot mark backfill done without queue_id. Maybe it wasn't actually inserted in the database?")
  181. return
  182. }
  183. _, err := b.db.Exec("UPDATE backfill_queue SET completed_at=$1 WHERE queue_id=$2", time.Now(), b.QueueID)
  184. if err != nil {
  185. b.log.Warnfln("Failed to mark %s/%s as complete: %v", b.BackfillType, b.Priority, err)
  186. }
  187. }