backfill.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. "sync"
  24. "time"
  25. log "maunium.net/go/maulogger/v2"
  26. "maunium.net/go/mautrix/id"
  27. "maunium.net/go/mautrix/util/dbutil"
  28. )
  29. type BackfillType int
  30. const (
  31. BackfillImmediate BackfillType = 0
  32. BackfillForward BackfillType = 100
  33. BackfillDeferred BackfillType = 200
  34. )
  35. func (bt BackfillType) String() string {
  36. switch bt {
  37. case BackfillImmediate:
  38. return "IMMEDIATE"
  39. case BackfillForward:
  40. return "FORWARD"
  41. case BackfillDeferred:
  42. return "DEFERRED"
  43. }
  44. return "UNKNOWN"
  45. }
  46. type BackfillQuery struct {
  47. db *Database
  48. log log.Logger
  49. backfillQueryLock sync.Mutex
  50. }
  51. func (bq *BackfillQuery) New() *Backfill {
  52. return &Backfill{
  53. db: bq.db,
  54. log: bq.log,
  55. Portal: &PortalKey{},
  56. }
  57. }
  58. func (bq *BackfillQuery) NewWithValues(userID id.UserID, backfillType BackfillType, priority int, portal *PortalKey, timeStart *time.Time, maxBatchEvents, maxTotalEvents, batchDelay int) *Backfill {
  59. return &Backfill{
  60. db: bq.db,
  61. log: bq.log,
  62. UserID: userID,
  63. BackfillType: backfillType,
  64. Priority: priority,
  65. Portal: portal,
  66. TimeStart: timeStart,
  67. MaxBatchEvents: maxBatchEvents,
  68. MaxTotalEvents: maxTotalEvents,
  69. BatchDelay: batchDelay,
  70. }
  71. }
  72. const (
  73. getNextBackfillQuery = `
  74. SELECT queue_id, user_mxid, type, priority, portal_jid, portal_receiver, time_start, max_batch_events, max_total_events, batch_delay
  75. FROM backfill_queue
  76. WHERE user_mxid=$1
  77. AND type IN (%s)
  78. AND (
  79. dispatch_time IS NULL
  80. OR (
  81. dispatch_time < current_timestamp - interval '15 minutes'
  82. AND completed_at IS NULL
  83. )
  84. )
  85. ORDER BY type, priority, queue_id
  86. LIMIT 1
  87. `
  88. )
  89. // GetNext returns the next backfill to perform
  90. func (bq *BackfillQuery) GetNext(userID id.UserID, backfillTypes []BackfillType) (backfill *Backfill) {
  91. bq.backfillQueryLock.Lock()
  92. defer bq.backfillQueryLock.Unlock()
  93. types := []string{}
  94. for _, backfillType := range backfillTypes {
  95. types = append(types, strconv.Itoa(int(backfillType)))
  96. }
  97. rows, err := bq.db.Query(fmt.Sprintf(getNextBackfillQuery, strings.Join(types, ",")), userID)
  98. if err != nil || rows == nil {
  99. bq.log.Error(err)
  100. return
  101. }
  102. defer rows.Close()
  103. if rows.Next() {
  104. backfill = bq.New().Scan(rows)
  105. }
  106. return
  107. }
  108. func (bq *BackfillQuery) DeleteAll(userID id.UserID) {
  109. bq.backfillQueryLock.Lock()
  110. defer bq.backfillQueryLock.Unlock()
  111. _, err := bq.db.Exec("DELETE FROM backfill_queue WHERE user_mxid=$1", userID)
  112. if err != nil {
  113. bq.log.Warnfln("Failed to delete backfill queue items for %s: %v", userID, err)
  114. }
  115. }
  116. func (bq *BackfillQuery) DeleteAllForPortal(userID id.UserID, portalKey PortalKey) {
  117. bq.backfillQueryLock.Lock()
  118. defer bq.backfillQueryLock.Unlock()
  119. _, err := bq.db.Exec(`
  120. DELETE FROM backfill_queue
  121. WHERE user_mxid=$1
  122. AND portal_jid=$2
  123. AND portal_receiver=$3
  124. `, userID, portalKey.JID, portalKey.Receiver)
  125. if err != nil {
  126. bq.log.Warnfln("Failed to delete backfill queue items for %s/%s: %v", userID, portalKey.JID, err)
  127. }
  128. }
  129. type Backfill struct {
  130. db *Database
  131. log log.Logger
  132. // Fields
  133. QueueID int
  134. UserID id.UserID
  135. BackfillType BackfillType
  136. Priority int
  137. Portal *PortalKey
  138. TimeStart *time.Time
  139. MaxBatchEvents int
  140. MaxTotalEvents int
  141. BatchDelay int
  142. DispatchTime *time.Time
  143. CompletedAt *time.Time
  144. }
  145. func (b *Backfill) String() string {
  146. 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}",
  147. b.QueueID, b.UserID, b.BackfillType, b.Priority, b.Portal, b.TimeStart, b.MaxBatchEvents, b.MaxTotalEvents, b.BatchDelay, b.CompletedAt, b.DispatchTime,
  148. )
  149. }
  150. func (b *Backfill) Scan(row dbutil.Scannable) *Backfill {
  151. 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)
  152. if err != nil {
  153. if !errors.Is(err, sql.ErrNoRows) {
  154. b.log.Errorln("Database scan failed:", err)
  155. }
  156. return nil
  157. }
  158. return b
  159. }
  160. func (b *Backfill) Insert() {
  161. b.db.Backfill.backfillQueryLock.Lock()
  162. defer b.db.Backfill.backfillQueryLock.Unlock()
  163. rows, err := b.db.Query(`
  164. INSERT INTO backfill_queue
  165. (user_mxid, type, priority, portal_jid, portal_receiver, time_start, max_batch_events, max_total_events, batch_delay, dispatch_time, completed_at)
  166. VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
  167. RETURNING queue_id
  168. `, b.UserID, b.BackfillType, b.Priority, b.Portal.JID, b.Portal.Receiver, b.TimeStart, b.MaxBatchEvents, b.MaxTotalEvents, b.BatchDelay, b.DispatchTime, b.CompletedAt)
  169. defer rows.Close()
  170. if err != nil || !rows.Next() {
  171. b.log.Warnfln("Failed to insert %v/%s with priority %d: %v", b.BackfillType, b.Portal.JID, b.Priority, err)
  172. return
  173. }
  174. err = rows.Scan(&b.QueueID)
  175. if err != nil {
  176. b.log.Warnfln("Failed to insert %s/%s with priority %s: %v", b.BackfillType, b.Portal.JID, b.Priority, err)
  177. }
  178. }
  179. func (b *Backfill) MarkDispatched() {
  180. b.db.Backfill.backfillQueryLock.Lock()
  181. defer b.db.Backfill.backfillQueryLock.Unlock()
  182. if b.QueueID == 0 {
  183. b.log.Errorf("Cannot mark backfill as dispatched without queue_id. Maybe it wasn't actually inserted in the database?")
  184. return
  185. }
  186. _, err := b.db.Exec("UPDATE backfill_queue SET dispatch_time=$1 WHERE queue_id=$2", time.Now(), b.QueueID)
  187. if err != nil {
  188. b.log.Warnfln("Failed to mark %s/%s as dispatched: %v", b.BackfillType, b.Priority, err)
  189. }
  190. }
  191. func (b *Backfill) MarkDone() {
  192. b.db.Backfill.backfillQueryLock.Lock()
  193. defer b.db.Backfill.backfillQueryLock.Unlock()
  194. if b.QueueID == 0 {
  195. b.log.Errorf("Cannot mark backfill done without queue_id. Maybe it wasn't actually inserted in the database?")
  196. return
  197. }
  198. _, err := b.db.Exec("UPDATE backfill_queue SET completed_at=$1 WHERE queue_id=$2", time.Now(), b.QueueID)
  199. if err != nil {
  200. b.log.Warnfln("Failed to mark %s/%s as complete: %v", b.BackfillType, b.Priority, err)
  201. }
  202. }
  203. func (bq *BackfillQuery) NewBackfillState(userID id.UserID, portalKey *PortalKey) *BackfillState {
  204. return &BackfillState{
  205. db: bq.db,
  206. log: bq.log,
  207. UserID: userID,
  208. Portal: portalKey,
  209. }
  210. }
  211. const (
  212. getBackfillState = `
  213. SELECT user_mxid, portal_jid, portal_receiver, processing_batch, backfill_complete, first_expected_ts
  214. FROM backfill_state
  215. WHERE user_mxid=$1
  216. AND portal_jid=$2
  217. AND portal_receiver=$3
  218. `
  219. )
  220. type BackfillState struct {
  221. db *Database
  222. log log.Logger
  223. // Fields
  224. UserID id.UserID
  225. Portal *PortalKey
  226. ProcessingBatch bool
  227. BackfillComplete bool
  228. FirstExpectedTimestamp uint64
  229. }
  230. func (b *BackfillState) Scan(row dbutil.Scannable) *BackfillState {
  231. err := row.Scan(&b.UserID, &b.Portal.JID, &b.Portal.Receiver, &b.ProcessingBatch, &b.BackfillComplete, &b.FirstExpectedTimestamp)
  232. if err != nil {
  233. if !errors.Is(err, sql.ErrNoRows) {
  234. b.log.Errorln("Database scan failed:", err)
  235. }
  236. return nil
  237. }
  238. return b
  239. }
  240. func (b *BackfillState) Upsert() {
  241. _, err := b.db.Exec(`
  242. INSERT INTO backfill_state
  243. (user_mxid, portal_jid, portal_receiver, processing_batch, backfill_complete, first_expected_ts)
  244. VALUES ($1, $2, $3, $4, $5, $6)
  245. ON CONFLICT (user_mxid, portal_jid, portal_receiver)
  246. DO UPDATE SET
  247. processing_batch=EXCLUDED.processing_batch,
  248. backfill_complete=EXCLUDED.backfill_complete,
  249. first_expected_ts=EXCLUDED.first_expected_ts`,
  250. b.UserID, b.Portal.JID, b.Portal.Receiver, b.ProcessingBatch, b.BackfillComplete, b.FirstExpectedTimestamp)
  251. if err != nil {
  252. b.log.Warnfln("Failed to insert backfill state for %s: %v", b.Portal.JID, err)
  253. }
  254. }
  255. func (b *BackfillState) SetProcessingBatch(processing bool) {
  256. b.ProcessingBatch = processing
  257. b.Upsert()
  258. }
  259. func (bq *BackfillQuery) GetBackfillState(userID id.UserID, portalKey *PortalKey) (backfillState *BackfillState) {
  260. rows, err := bq.db.Query(getBackfillState, userID, portalKey.JID, portalKey.Receiver)
  261. if err != nil || rows == nil {
  262. bq.log.Error(err)
  263. return
  264. }
  265. defer rows.Close()
  266. if rows.Next() {
  267. backfillState = bq.NewBackfillState(userID, portalKey).Scan(rows)
  268. }
  269. return
  270. }