backfillqueue.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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 dispatch_time IS NULL
  76. ORDER BY type, priority, queue_id
  77. LIMIT 1
  78. `
  79. )
  80. // GetNext returns the next backfill to perform
  81. func (bq *BackfillQuery) GetNext(userID id.UserID, backfillTypes []BackfillType) (backfill *Backfill) {
  82. types := []string{}
  83. for _, backfillType := range backfillTypes {
  84. types = append(types, strconv.Itoa(int(backfillType)))
  85. }
  86. rows, err := bq.db.Query(fmt.Sprintf(getNextBackfillQuery, strings.Join(types, ",")), userID)
  87. if err != nil || rows == nil {
  88. bq.log.Error(err)
  89. return
  90. }
  91. defer rows.Close()
  92. if rows.Next() {
  93. backfill = bq.New().Scan(rows)
  94. }
  95. return
  96. }
  97. func (bq *BackfillQuery) DeleteAll(userID id.UserID) {
  98. _, err := bq.db.Exec("DELETE FROM backfill_queue WHERE user_mxid=$1", userID)
  99. if err != nil {
  100. bq.log.Warnfln("Failed to delete backfill queue items for %s: %v", userID, err)
  101. }
  102. }
  103. func (bq *BackfillQuery) DeleteAllForPortal(userID id.UserID, portalKey PortalKey) {
  104. _, err := bq.db.Exec(`
  105. DELETE FROM backfill_queue
  106. WHERE user_mxid=$1
  107. AND portal_jid=$2
  108. AND portal_receiver=$3
  109. `, userID, portalKey.JID, portalKey.Receiver)
  110. if err != nil {
  111. bq.log.Warnfln("Failed to delete backfill queue items for %s/%s: %v", userID, portalKey.JID, err)
  112. }
  113. }
  114. type Backfill struct {
  115. db *Database
  116. log log.Logger
  117. // Fields
  118. QueueID int
  119. UserID id.UserID
  120. BackfillType BackfillType
  121. Priority int
  122. Portal *PortalKey
  123. TimeStart *time.Time
  124. MaxBatchEvents int
  125. MaxTotalEvents int
  126. BatchDelay int
  127. DispatchTime *time.Time
  128. CompletedAt *time.Time
  129. }
  130. func (b *Backfill) String() string {
  131. 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}",
  132. b.QueueID, b.UserID, b.BackfillType, b.Priority, b.Portal, b.TimeStart, b.MaxBatchEvents, b.MaxTotalEvents, b.BatchDelay, b.CompletedAt, b.DispatchTime,
  133. )
  134. }
  135. func (b *Backfill) Scan(row Scannable) *Backfill {
  136. 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)
  137. if err != nil {
  138. if !errors.Is(err, sql.ErrNoRows) {
  139. b.log.Errorln("Database scan failed:", err)
  140. }
  141. return nil
  142. }
  143. return b
  144. }
  145. func (b *Backfill) Insert() {
  146. rows, err := b.db.Query(`
  147. INSERT INTO backfill_queue
  148. (user_mxid, type, priority, portal_jid, portal_receiver, time_start, max_batch_events, max_total_events, batch_delay, dispatch_time, completed_at)
  149. VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
  150. RETURNING queue_id
  151. `, b.UserID, b.BackfillType, b.Priority, b.Portal.JID, b.Portal.Receiver, b.TimeStart, b.MaxBatchEvents, b.MaxTotalEvents, b.BatchDelay, b.DispatchTime, b.CompletedAt)
  152. defer rows.Close()
  153. if err != nil || !rows.Next() {
  154. b.log.Warnfln("Failed to insert %v/%s with priority %d: %v", b.BackfillType, b.Portal.JID, b.Priority, err)
  155. return
  156. }
  157. err = rows.Scan(&b.QueueID)
  158. if err != nil {
  159. b.log.Warnfln("Failed to insert %s/%s with priority %s: %v", b.BackfillType, b.Portal.JID, b.Priority, err)
  160. }
  161. }
  162. func (b *Backfill) MarkDispatched() {
  163. if b.QueueID == 0 {
  164. b.log.Errorf("Cannot mark backfill as dispatched without queue_id. Maybe it wasn't actually inserted in the database?")
  165. return
  166. }
  167. _, err := b.db.Exec("UPDATE backfill_queue SET dispatch_time=$1 WHERE queue_id=$2", time.Now(), b.QueueID)
  168. if err != nil {
  169. b.log.Warnfln("Failed to mark %s/%s as dispatched: %v", b.BackfillType, b.Priority, err)
  170. }
  171. }
  172. func (b *Backfill) MarkDone() {
  173. if b.QueueID == 0 {
  174. b.log.Errorf("Cannot mark backfill done without queue_id. Maybe it wasn't actually inserted in the database?")
  175. return
  176. }
  177. _, err := b.db.Exec("UPDATE backfill_queue SET completed_at=$1 WHERE queue_id=$2", time.Now(), b.QueueID)
  178. if err != nil {
  179. b.log.Warnfln("Failed to mark %s/%s as complete: %v", b.BackfillType, b.Priority, err)
  180. }
  181. }