backfillqueue.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 main
  17. import (
  18. "time"
  19. log "maunium.net/go/maulogger/v2"
  20. "maunium.net/go/mautrix-whatsapp/database"
  21. )
  22. type BackfillQueue struct {
  23. BackfillQuery *database.BackfillQuery
  24. ImmediateBackfillRequests chan *database.Backfill
  25. DeferredBackfillRequests chan *database.Backfill
  26. ReCheckQueue chan bool
  27. log log.Logger
  28. }
  29. // RunLoop fetches backfills from the database, prioritizing immediate and forward backfills
  30. func (bq *BackfillQueue) RunLoop(user *User) {
  31. for {
  32. if backfill := bq.BackfillQuery.GetNext(user.MXID); backfill != nil {
  33. if backfill.BackfillType == database.BackfillImmediate || backfill.BackfillType == database.BackfillForward {
  34. bq.ImmediateBackfillRequests <- backfill
  35. } else if backfill.BackfillType == database.BackfillDeferred {
  36. select {
  37. case <-bq.ReCheckQueue:
  38. // If a queue re-check is requested, interrupt sending the
  39. // backfill request to the deferred channel so that
  40. // immediate backfills can happen ASAP.
  41. continue
  42. case bq.DeferredBackfillRequests <- backfill:
  43. }
  44. } else {
  45. bq.log.Debugfln("Unrecognized backfill type %d in queue", backfill.BackfillType)
  46. }
  47. backfill.MarkDispatched()
  48. } else {
  49. select {
  50. case <-bq.ReCheckQueue:
  51. case <-time.After(time.Minute):
  52. }
  53. }
  54. }
  55. }