backfillqueue.go 5.6 KB

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