historysync: lock earlier to prevent races and duplicate messages

Closes BRI-2709
This commit is contained in:
Sumner Evans 2022-04-04 16:07:25 -06:00
parent 54534f6b42
commit 748c9509a1
No known key found for this signature in database
GPG key ID: 8904527AB50022FD

View file

@ -100,8 +100,16 @@ func (user *User) handleBackfillRequestsLoop(backfillRequests chan *database.Bac
portal.Update() portal.Update()
} }
user.createOrUpdatePortalAndBackfillWithLock(req, conv, portal)
}
}
func (user *User) createOrUpdatePortalAndBackfillWithLock(req *database.Backfill, conv *database.HistorySyncConversation, portal *Portal) {
portal.backfillLock.Lock()
defer portal.backfillLock.Unlock()
if !user.shouldCreatePortalForHistorySync(conv, portal) { if !user.shouldCreatePortalForHistorySync(conv, portal) {
continue return
} }
if len(portal.MXID) == 0 { if len(portal.MXID) == 0 {
@ -109,7 +117,7 @@ func (user *User) handleBackfillRequestsLoop(backfillRequests chan *database.Bac
err := portal.CreateMatrixRoom(user, nil, true, false) err := portal.CreateMatrixRoom(user, nil, true, false)
if err != nil { if err != nil {
user.log.Warnfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err) user.log.Warnfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
continue return
} }
} else { } else {
portal.UpdateMatrixRoom(user, nil) portal.UpdateMatrixRoom(user, nil)
@ -158,7 +166,6 @@ func (user *User) handleBackfillRequestsLoop(backfillRequests chan *database.Bac
if !conv.MarkedAsUnread && conv.UnreadCount == 0 { if !conv.MarkedAsUnread && conv.UnreadCount == 0 {
user.markSelfReadFull(portal) user.markSelfReadFull(portal)
} }
}
} }
func (user *User) shouldCreatePortalForHistorySync(conv *database.HistorySyncConversation, portal *Portal) bool { func (user *User) shouldCreatePortalForHistorySync(conv *database.HistorySyncConversation, portal *Portal) bool {
@ -298,9 +305,6 @@ var (
) )
func (portal *Portal) backfill(source *User, messages []*database.WrappedWebMessageInfo) []id.EventID { func (portal *Portal) backfill(source *User, messages []*database.WrappedWebMessageInfo) []id.EventID {
portal.backfillLock.Lock()
defer portal.backfillLock.Unlock()
var historyBatch, newBatch mautrix.ReqBatchSend var historyBatch, newBatch mautrix.ReqBatchSend
var historyBatchInfos, newBatchInfos []*wrappedInfo var historyBatchInfos, newBatchInfos []*wrappedInfo