backfillqueue.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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, timeEnd *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. TimeEnd: timeEnd,
  63. MaxBatchEvents: maxBatchEvents,
  64. MaxTotalEvents: maxTotalEvents,
  65. BatchDelay: batchDelay,
  66. }
  67. }
  68. const (
  69. getNextBackfillQuery = `
  70. SELECT queue_id, user_mxid, type, priority, portal_jid, portal_receiver, time_start, time_end, max_batch_events, max_total_events, batch_delay
  71. FROM backfill_queue
  72. WHERE user_mxid=$1
  73. AND completed_at IS NULL
  74. ORDER BY type, priority, queue_id
  75. LIMIT 1
  76. `
  77. )
  78. // GetNext returns the next backfill to perform
  79. func (bq *BackfillQuery) GetNext(userID id.UserID) (backfill *Backfill) {
  80. rows, err := bq.db.Query(getNextBackfillQuery, userID)
  81. defer rows.Close()
  82. if err != nil || rows == nil {
  83. bq.log.Error(err)
  84. return
  85. }
  86. if rows.Next() {
  87. backfill = bq.New().Scan(rows)
  88. }
  89. return
  90. }
  91. func (bq *BackfillQuery) DeleteAll(userID id.UserID) error {
  92. _, err := bq.db.Exec("DELETE FROM backfill_queue WHERE user_mxid=$1", userID)
  93. return err
  94. }
  95. func (bq *BackfillQuery) DeleteAllForPortal(userID id.UserID, portalKey PortalKey) error {
  96. _, err := bq.db.Exec(`
  97. DELETE FROM backfill_queue
  98. WHERE user_mxid=$1
  99. AND portal_jid=$2
  100. AND portal_receiver=$3
  101. `, userID, portalKey.JID, portalKey.Receiver)
  102. return err
  103. }
  104. type Backfill struct {
  105. db *Database
  106. log log.Logger
  107. // Fields
  108. QueueID int
  109. UserID id.UserID
  110. BackfillType BackfillType
  111. Priority int
  112. Portal *PortalKey
  113. TimeStart *time.Time
  114. TimeEnd *time.Time
  115. MaxBatchEvents int
  116. MaxTotalEvents int
  117. BatchDelay int
  118. CompletedAt *time.Time
  119. }
  120. func (b *Backfill) String() string {
  121. 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}",
  122. b.QueueID, b.UserID, b.BackfillType, b.Priority, b.Portal, b.TimeStart, b.TimeEnd, b.MaxBatchEvents, b.MaxTotalEvents, b.BatchDelay, b.CompletedAt,
  123. )
  124. }
  125. func (b *Backfill) Scan(row Scannable) *Backfill {
  126. 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)
  127. if err != nil {
  128. if !errors.Is(err, sql.ErrNoRows) {
  129. b.log.Errorln("Database scan failed:", err)
  130. }
  131. return nil
  132. }
  133. return b
  134. }
  135. func (b *Backfill) Insert() {
  136. rows, err := b.db.Query(`
  137. INSERT INTO backfill_queue
  138. (user_mxid, type, priority, portal_jid, portal_receiver, time_start, time_end, max_batch_events, max_total_events, batch_delay, completed_at)
  139. VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
  140. RETURNING queue_id
  141. `, b.UserID, b.BackfillType, b.Priority, b.Portal.JID, b.Portal.Receiver, b.TimeStart, b.TimeEnd, b.MaxBatchEvents, b.MaxTotalEvents, b.BatchDelay, b.CompletedAt)
  142. defer rows.Close()
  143. if err != nil || !rows.Next() {
  144. b.log.Warnfln("Failed to insert %v/%s with priority %d: %v", b.BackfillType, b.Portal.JID, b.Priority, err)
  145. return
  146. }
  147. err = rows.Scan(&b.QueueID)
  148. if err != nil {
  149. b.log.Warnfln("Failed to insert %s/%s with priority %s: %v", b.BackfillType, b.Portal.JID, b.Priority, err)
  150. }
  151. }
  152. func (b *Backfill) MarkDone() {
  153. if b.QueueID == 0 {
  154. b.log.Errorf("Cannot delete backfill without queue_id. Maybe it wasn't actually inserted in the database?")
  155. return
  156. }
  157. _, err := b.db.Exec("UPDATE backfill_queue SET completed_at=$1 WHERE queue_id=$2", time.Now(), b.QueueID)
  158. if err != nil {
  159. b.log.Warnfln("Failed to mark %s/%s as complete: %v", b.BackfillType, b.Priority, err)
  160. }
  161. }