2021-01-08 17:59:06 +01:00
|
|
|
package streams
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-04-07 16:08:19 +02:00
|
|
|
"database/sql"
|
2022-04-20 17:06:46 +02:00
|
|
|
"fmt"
|
2022-04-26 10:53:17 +02:00
|
|
|
"sort"
|
2021-01-29 17:32:54 +01:00
|
|
|
"sync"
|
|
|
|
"time"
|
2021-01-08 17:59:06 +01:00
|
|
|
|
2022-04-19 10:46:45 +02:00
|
|
|
"github.com/matrix-org/dendrite/internal/caching"
|
2022-04-26 10:53:17 +02:00
|
|
|
roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
|
2022-08-11 18:23:35 +02:00
|
|
|
"github.com/matrix-org/dendrite/syncapi/internal"
|
|
|
|
"github.com/matrix-org/dendrite/syncapi/storage"
|
2021-01-08 17:59:06 +01:00
|
|
|
"github.com/matrix-org/dendrite/syncapi/types"
|
|
|
|
userapi "github.com/matrix-org/dendrite/userapi/api"
|
2022-08-05 14:27:27 +02:00
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2022-08-11 18:23:35 +02:00
|
|
|
"github.com/sirupsen/logrus"
|
2022-04-26 10:53:17 +02:00
|
|
|
"github.com/tidwall/gjson"
|
2021-01-29 17:32:54 +01:00
|
|
|
"go.uber.org/atomic"
|
2022-08-05 14:27:27 +02:00
|
|
|
|
|
|
|
"github.com/matrix-org/dendrite/syncapi/notifier"
|
2021-01-08 17:59:06 +01:00
|
|
|
)
|
|
|
|
|
2021-01-29 17:32:54 +01:00
|
|
|
// The max number of per-room goroutines to have running.
|
|
|
|
// Too high and this will consume lots of CPU, too low and complete
|
|
|
|
// sync responses will take longer to process.
|
|
|
|
const PDU_STREAM_WORKERS = 256
|
|
|
|
|
|
|
|
// The maximum number of tasks that can be queued in total before
|
|
|
|
// backpressure will build up and the rests will start to block.
|
|
|
|
const PDU_STREAM_QUEUESIZE = PDU_STREAM_WORKERS * 8
|
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
type PDUStreamProvider struct {
|
|
|
|
StreamProvider
|
2021-01-29 17:32:54 +01:00
|
|
|
|
|
|
|
tasks chan func()
|
|
|
|
workers atomic.Int32
|
2022-04-19 10:46:45 +02:00
|
|
|
// userID+deviceID -> lazy loading cache
|
2022-05-06 15:33:34 +02:00
|
|
|
lazyLoadCache caching.LazyLoadCache
|
2022-05-05 10:56:03 +02:00
|
|
|
rsAPI roomserverAPI.SyncRoomserverAPI
|
2022-08-05 14:27:27 +02:00
|
|
|
notifier *notifier.Notifier
|
2021-01-29 17:32:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *PDUStreamProvider) worker() {
|
|
|
|
defer p.workers.Dec()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case f := <-p.tasks:
|
|
|
|
f()
|
|
|
|
case <-time.After(time.Second * 10):
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *PDUStreamProvider) queue(f func()) {
|
|
|
|
if p.workers.Load() < PDU_STREAM_WORKERS {
|
|
|
|
p.workers.Inc()
|
|
|
|
go p.worker()
|
|
|
|
}
|
|
|
|
p.tasks <- f
|
2021-01-08 17:59:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *PDUStreamProvider) Setup() {
|
|
|
|
p.StreamProvider.Setup()
|
2021-01-29 17:32:54 +01:00
|
|
|
p.tasks = make(chan func(), PDU_STREAM_QUEUESIZE)
|
2021-01-08 17:59:06 +01:00
|
|
|
|
|
|
|
p.latestMutex.Lock()
|
|
|
|
defer p.latestMutex.Unlock()
|
|
|
|
|
|
|
|
id, err := p.DB.MaxStreamPositionForPDUs(context.Background())
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
p.latest = id
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *PDUStreamProvider) CompleteSync(
|
|
|
|
ctx context.Context,
|
|
|
|
req *types.SyncRequest,
|
|
|
|
) types.StreamPosition {
|
|
|
|
from := types.StreamPosition(0)
|
|
|
|
to := p.LatestPosition(ctx)
|
|
|
|
|
|
|
|
// Get the current sync position which we will base the sync response on.
|
|
|
|
// For complete syncs, we want to start at the most recent events and work
|
|
|
|
// backwards, so that we show the most recent events in the room.
|
|
|
|
r := types.Range{
|
|
|
|
From: to,
|
|
|
|
To: 0,
|
|
|
|
Backwards: true,
|
|
|
|
}
|
|
|
|
|
|
|
|
// Extract room state and recent events for all rooms the user is joined to.
|
|
|
|
joinedRoomIDs, err := p.DB.RoomIDsWithMembership(ctx, req.Device.UserID, gomatrixserverlib.Join)
|
|
|
|
if err != nil {
|
|
|
|
req.Log.WithError(err).Error("p.DB.RoomIDsWithMembership failed")
|
|
|
|
return from
|
|
|
|
}
|
|
|
|
|
2021-01-19 19:00:42 +01:00
|
|
|
stateFilter := req.Filter.Room.State
|
|
|
|
eventFilter := req.Filter.Room.Timeline
|
2021-01-08 17:59:06 +01:00
|
|
|
|
2022-04-07 16:08:19 +02:00
|
|
|
if err = p.addIgnoredUsersToFilter(ctx, req, &eventFilter); err != nil {
|
|
|
|
req.Log.WithError(err).Error("unable to update event filter with ignored users")
|
|
|
|
}
|
|
|
|
|
2022-08-05 14:27:27 +02:00
|
|
|
// Invalidate the lazyLoadCache, otherwise we end up with missing displaynames/avatars
|
|
|
|
// TODO: This might be inefficient, when joined to many and/or large rooms.
|
|
|
|
for _, roomID := range joinedRoomIDs {
|
|
|
|
joinedUsers := p.notifier.JoinedUsers(roomID)
|
|
|
|
for _, sharedUser := range joinedUsers {
|
|
|
|
p.lazyLoadCache.InvalidateLazyLoadedUser(req.Device, roomID, sharedUser)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
// Build up a /sync response. Add joined rooms.
|
2021-01-29 17:32:54 +01:00
|
|
|
var reqMutex sync.Mutex
|
|
|
|
var reqWaitGroup sync.WaitGroup
|
|
|
|
reqWaitGroup.Add(len(joinedRoomIDs))
|
|
|
|
for _, room := range joinedRoomIDs {
|
|
|
|
roomID := room
|
|
|
|
p.queue(func() {
|
|
|
|
defer reqWaitGroup.Done()
|
|
|
|
|
2022-08-01 16:55:56 +02:00
|
|
|
jr, jerr := p.getJoinResponseForCompleteSync(
|
2022-08-11 18:23:35 +02:00
|
|
|
ctx, roomID, r, &stateFilter, &eventFilter, req.WantFullState, req.Device, false,
|
2021-01-29 17:32:54 +01:00
|
|
|
)
|
2022-08-01 16:55:56 +02:00
|
|
|
if jerr != nil {
|
|
|
|
req.Log.WithError(jerr).Error("p.getJoinResponseForCompleteSync failed")
|
2021-01-29 17:32:54 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
reqMutex.Lock()
|
|
|
|
defer reqMutex.Unlock()
|
|
|
|
req.Response.Rooms.Join[roomID] = *jr
|
|
|
|
req.Rooms[roomID] = gomatrixserverlib.Join
|
|
|
|
})
|
2021-01-08 17:59:06 +01:00
|
|
|
}
|
|
|
|
|
2021-01-29 17:32:54 +01:00
|
|
|
reqWaitGroup.Wait()
|
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
// Add peeked rooms.
|
|
|
|
peeks, err := p.DB.PeeksInRange(ctx, req.Device.UserID, req.Device.ID, r)
|
|
|
|
if err != nil {
|
|
|
|
req.Log.WithError(err).Error("p.DB.PeeksInRange failed")
|
|
|
|
return from
|
|
|
|
}
|
|
|
|
for _, peek := range peeks {
|
|
|
|
if !peek.Deleted {
|
|
|
|
var jr *types.JoinResponse
|
|
|
|
jr, err = p.getJoinResponseForCompleteSync(
|
2022-08-11 18:23:35 +02:00
|
|
|
ctx, peek.RoomID, r, &stateFilter, &eventFilter, req.WantFullState, req.Device, true,
|
2021-01-08 17:59:06 +01:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
req.Log.WithError(err).Error("p.getJoinResponseForCompleteSync failed")
|
|
|
|
return from
|
|
|
|
}
|
|
|
|
req.Response.Rooms.Peek[peek.RoomID] = *jr
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return to
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *PDUStreamProvider) IncrementalSync(
|
|
|
|
ctx context.Context,
|
|
|
|
req *types.SyncRequest,
|
|
|
|
from, to types.StreamPosition,
|
|
|
|
) (newPos types.StreamPosition) {
|
|
|
|
r := types.Range{
|
|
|
|
From: from,
|
|
|
|
To: to,
|
|
|
|
Backwards: from > to,
|
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
|
|
|
var stateDeltas []types.StateDelta
|
2022-08-19 15:32:24 +02:00
|
|
|
var syncJoinedRooms []string
|
2021-01-08 17:59:06 +01:00
|
|
|
|
2021-01-19 19:00:42 +01:00
|
|
|
stateFilter := req.Filter.Room.State
|
|
|
|
eventFilter := req.Filter.Room.Timeline
|
2021-01-08 17:59:06 +01:00
|
|
|
|
|
|
|
if req.WantFullState {
|
2022-08-19 15:32:24 +02:00
|
|
|
if stateDeltas, syncJoinedRooms, err = p.DB.GetStateDeltasForFullStateSync(ctx, req.Device, r, req.Device.UserID, &stateFilter); err != nil {
|
2021-01-08 17:59:06 +01:00
|
|
|
req.Log.WithError(err).Error("p.DB.GetStateDeltasForFullStateSync failed")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
2022-08-19 15:32:24 +02:00
|
|
|
if stateDeltas, syncJoinedRooms, err = p.DB.GetStateDeltas(ctx, req.Device, r, req.Device.UserID, &stateFilter); err != nil {
|
2021-01-08 17:59:06 +01:00
|
|
|
req.Log.WithError(err).Error("p.DB.GetStateDeltas failed")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-19 15:32:24 +02:00
|
|
|
for _, roomID := range syncJoinedRooms {
|
2021-01-08 17:59:06 +01:00
|
|
|
req.Rooms[roomID] = gomatrixserverlib.Join
|
|
|
|
}
|
|
|
|
|
2022-03-25 13:38:16 +01:00
|
|
|
if len(stateDeltas) == 0 {
|
|
|
|
return to
|
|
|
|
}
|
|
|
|
|
2022-04-07 16:08:19 +02:00
|
|
|
if err = p.addIgnoredUsersToFilter(ctx, req, &eventFilter); err != nil {
|
|
|
|
req.Log.WithError(err).Error("unable to update event filter with ignored users")
|
|
|
|
}
|
|
|
|
|
2022-03-25 13:38:16 +01:00
|
|
|
newPos = from
|
2021-01-08 17:59:06 +01:00
|
|
|
for _, delta := range stateDeltas {
|
2022-08-25 14:42:47 +02:00
|
|
|
newRange := r
|
|
|
|
// If this room was joined in this sync, try to fetch
|
|
|
|
// as much timeline events as allowed by the filter.
|
|
|
|
if delta.NewlyJoined {
|
|
|
|
// Reverse the range, so we get the most recent first.
|
|
|
|
// This will be limited by the eventFilter.
|
|
|
|
newRange = types.Range{
|
|
|
|
From: r.To,
|
|
|
|
To: 0,
|
|
|
|
Backwards: true,
|
|
|
|
}
|
|
|
|
}
|
2022-03-25 13:38:16 +01:00
|
|
|
var pos types.StreamPosition
|
2022-08-25 14:42:47 +02:00
|
|
|
if pos, err = p.addRoomDeltaToResponse(ctx, req.Device, newRange, delta, &eventFilter, &stateFilter, req.Response); err != nil {
|
2021-01-08 17:59:06 +01:00
|
|
|
req.Log.WithError(err).Error("d.addRoomDeltaToResponse failed")
|
2022-03-25 13:38:16 +01:00
|
|
|
return to
|
|
|
|
}
|
2022-08-25 14:42:47 +02:00
|
|
|
// Reset the position, as it is only for the special case of newly joined rooms
|
|
|
|
if delta.NewlyJoined {
|
|
|
|
pos = newRange.From
|
|
|
|
}
|
2022-03-25 13:38:16 +01:00
|
|
|
switch {
|
|
|
|
case r.Backwards && pos < newPos:
|
|
|
|
fallthrough
|
|
|
|
case !r.Backwards && pos > newPos:
|
|
|
|
newPos = pos
|
2021-01-08 17:59:06 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-25 13:38:16 +01:00
|
|
|
return newPos
|
2021-01-08 17:59:06 +01:00
|
|
|
}
|
|
|
|
|
2022-04-20 17:06:46 +02:00
|
|
|
// nolint:gocyclo
|
2021-01-08 17:59:06 +01:00
|
|
|
func (p *PDUStreamProvider) addRoomDeltaToResponse(
|
|
|
|
ctx context.Context,
|
|
|
|
device *userapi.Device,
|
|
|
|
r types.Range,
|
|
|
|
delta types.StateDelta,
|
2021-01-19 19:00:42 +01:00
|
|
|
eventFilter *gomatrixserverlib.RoomEventFilter,
|
2022-04-19 10:46:45 +02:00
|
|
|
stateFilter *gomatrixserverlib.StateFilter,
|
2021-01-08 17:59:06 +01:00
|
|
|
res *types.Response,
|
2022-03-25 13:38:16 +01:00
|
|
|
) (types.StreamPosition, error) {
|
2021-01-08 17:59:06 +01:00
|
|
|
if delta.MembershipPos > 0 && delta.Membership == gomatrixserverlib.Leave {
|
|
|
|
// make sure we don't leak recent events after the leave event.
|
|
|
|
// TODO: History visibility makes this somewhat complex to handle correctly. For example:
|
|
|
|
// TODO: This doesn't work for join -> leave in a single /sync request (see events prior to join).
|
|
|
|
// TODO: This will fail on join -> leave -> sensitive msg -> join -> leave
|
|
|
|
// in a single /sync request
|
|
|
|
// This is all "okay" assuming history_visibility == "shared" which it is by default.
|
|
|
|
r.To = delta.MembershipPos
|
|
|
|
}
|
|
|
|
recentStreamEvents, limited, err := p.DB.RecentEvents(
|
|
|
|
ctx, delta.RoomID, r,
|
2021-01-19 19:00:42 +01:00
|
|
|
eventFilter, true, true,
|
2021-01-08 17:59:06 +01:00
|
|
|
)
|
|
|
|
if err != nil {
|
2022-04-20 17:06:46 +02:00
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return r.To, nil
|
|
|
|
}
|
|
|
|
return r.From, fmt.Errorf("p.DB.RecentEvents: %w", err)
|
2021-01-08 17:59:06 +01:00
|
|
|
}
|
|
|
|
recentEvents := p.DB.StreamEventsToEvents(device, recentStreamEvents)
|
|
|
|
delta.StateEvents = removeDuplicates(delta.StateEvents, recentEvents) // roll back
|
|
|
|
prevBatch, err := p.DB.GetBackwardTopologyPos(ctx, recentStreamEvents)
|
|
|
|
if err != nil {
|
2022-04-20 17:06:46 +02:00
|
|
|
return r.From, fmt.Errorf("p.DB.GetBackwardTopologyPos: %w", err)
|
2021-01-08 17:59:06 +01:00
|
|
|
}
|
|
|
|
|
2022-03-25 13:38:16 +01:00
|
|
|
// If we didn't return any events at all then don't bother doing anything else.
|
2021-01-08 17:59:06 +01:00
|
|
|
if len(recentEvents) == 0 && len(delta.StateEvents) == 0 {
|
2022-03-25 13:38:16 +01:00
|
|
|
return r.To, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sort the events so that we can pick out the latest events from both sections.
|
|
|
|
recentEvents = gomatrixserverlib.HeaderedReverseTopologicalOrdering(recentEvents, gomatrixserverlib.TopologicalOrderByPrevEvents)
|
|
|
|
delta.StateEvents = gomatrixserverlib.HeaderedReverseTopologicalOrdering(delta.StateEvents, gomatrixserverlib.TopologicalOrderByAuthEvents)
|
|
|
|
|
|
|
|
// Work out what the highest stream position is for all of the events in this
|
|
|
|
// room that were returned.
|
|
|
|
latestPosition := r.To
|
|
|
|
updateLatestPosition := func(mostRecentEventID string) {
|
2022-04-19 10:46:45 +02:00
|
|
|
var pos types.StreamPosition
|
|
|
|
if _, pos, err = p.DB.PositionInTopology(ctx, mostRecentEventID); err == nil {
|
2022-03-25 13:38:16 +01:00
|
|
|
switch {
|
2022-08-02 10:43:48 +02:00
|
|
|
case r.Backwards && pos < latestPosition:
|
2022-03-25 13:38:16 +01:00
|
|
|
fallthrough
|
2022-08-02 10:43:48 +02:00
|
|
|
case !r.Backwards && pos > latestPosition:
|
2022-03-25 13:38:16 +01:00
|
|
|
latestPosition = pos
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-01-08 17:59:06 +01:00
|
|
|
|
2022-04-19 10:46:45 +02:00
|
|
|
if stateFilter.LazyLoadMembers {
|
|
|
|
delta.StateEvents, err = p.lazyLoadMembers(
|
2022-08-30 14:18:47 +02:00
|
|
|
ctx, delta.RoomID, true, limited, stateFilter,
|
2022-04-19 10:46:45 +02:00
|
|
|
device, recentEvents, delta.StateEvents,
|
|
|
|
)
|
2022-04-20 17:06:46 +02:00
|
|
|
if err != nil && err != sql.ErrNoRows {
|
|
|
|
return r.From, fmt.Errorf("p.lazyLoadMembers: %w", err)
|
2022-04-19 10:46:45 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-01 17:14:38 +02:00
|
|
|
hasMembershipChange := false
|
|
|
|
for _, recentEvent := range recentStreamEvents {
|
|
|
|
if recentEvent.Type() == gomatrixserverlib.MRoomMember && recentEvent.StateKey() != nil {
|
|
|
|
hasMembershipChange = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-11 18:23:35 +02:00
|
|
|
// Applies the history visibility rules
|
|
|
|
events, err := applyHistoryVisibilityFilter(ctx, p.DB, p.rsAPI, delta.RoomID, device.UserID, eventFilter.Limit, recentEvents)
|
|
|
|
if err != nil {
|
|
|
|
logrus.WithError(err).Error("unable to apply history visibility filter")
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(delta.StateEvents) > 0 {
|
|
|
|
updateLatestPosition(delta.StateEvents[len(delta.StateEvents)-1].EventID())
|
|
|
|
}
|
2022-08-25 14:42:47 +02:00
|
|
|
if len(events) > 0 {
|
|
|
|
updateLatestPosition(events[len(events)-1].EventID())
|
|
|
|
}
|
2022-08-11 18:23:35 +02:00
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
switch delta.Membership {
|
|
|
|
case gomatrixserverlib.Join:
|
|
|
|
jr := types.NewJoinResponse()
|
2022-04-01 17:14:38 +02:00
|
|
|
if hasMembershipChange {
|
2022-04-26 10:53:17 +02:00
|
|
|
p.addRoomSummary(ctx, jr, delta.RoomID, device.UserID, latestPosition)
|
2022-04-01 17:14:38 +02:00
|
|
|
}
|
2021-01-08 17:59:06 +01:00
|
|
|
jr.Timeline.PrevBatch = &prevBatch
|
2022-08-11 18:23:35 +02:00
|
|
|
jr.Timeline.Events = gomatrixserverlib.HeaderedToClientEvents(events, gomatrixserverlib.FormatSync)
|
|
|
|
// If we are limited by the filter AND the history visibility filter
|
|
|
|
// didn't "remove" events, return that the response is limited.
|
|
|
|
jr.Timeline.Limited = limited && len(events) == len(recentEvents)
|
2021-01-08 17:59:06 +01:00
|
|
|
jr.State.Events = gomatrixserverlib.HeaderedToClientEvents(delta.StateEvents, gomatrixserverlib.FormatSync)
|
|
|
|
res.Rooms.Join[delta.RoomID] = *jr
|
2021-01-13 15:32:49 +01:00
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
case gomatrixserverlib.Peek:
|
|
|
|
jr := types.NewJoinResponse()
|
|
|
|
jr.Timeline.PrevBatch = &prevBatch
|
2022-08-11 18:23:35 +02:00
|
|
|
// TODO: Apply history visibility on peeked rooms
|
2021-01-08 17:59:06 +01:00
|
|
|
jr.Timeline.Events = gomatrixserverlib.HeaderedToClientEvents(recentEvents, gomatrixserverlib.FormatSync)
|
|
|
|
jr.Timeline.Limited = limited
|
|
|
|
jr.State.Events = gomatrixserverlib.HeaderedToClientEvents(delta.StateEvents, gomatrixserverlib.FormatSync)
|
|
|
|
res.Rooms.Peek[delta.RoomID] = *jr
|
2021-01-13 15:32:49 +01:00
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
case gomatrixserverlib.Leave:
|
|
|
|
fallthrough // transitions to leave are the same as ban
|
2021-01-13 15:32:49 +01:00
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
case gomatrixserverlib.Ban:
|
|
|
|
lr := types.NewLeaveResponse()
|
|
|
|
lr.Timeline.PrevBatch = &prevBatch
|
2022-08-11 18:23:35 +02:00
|
|
|
lr.Timeline.Events = gomatrixserverlib.HeaderedToClientEvents(events, gomatrixserverlib.FormatSync)
|
|
|
|
// If we are limited by the filter AND the history visibility filter
|
|
|
|
// didn't "remove" events, return that the response is limited.
|
|
|
|
lr.Timeline.Limited = limited && len(events) == len(recentEvents)
|
2021-01-08 17:59:06 +01:00
|
|
|
lr.State.Events = gomatrixserverlib.HeaderedToClientEvents(delta.StateEvents, gomatrixserverlib.FormatSync)
|
|
|
|
res.Rooms.Leave[delta.RoomID] = *lr
|
|
|
|
}
|
|
|
|
|
2022-03-25 13:38:16 +01:00
|
|
|
return latestPosition, nil
|
2021-01-08 17:59:06 +01:00
|
|
|
}
|
|
|
|
|
2022-08-11 18:23:35 +02:00
|
|
|
// applyHistoryVisibilityFilter gets the current room state and supplies it to ApplyHistoryVisibilityFilter, to make
|
|
|
|
// sure we always return the required events in the timeline.
|
|
|
|
func applyHistoryVisibilityFilter(
|
|
|
|
ctx context.Context,
|
|
|
|
db storage.Database,
|
|
|
|
rsAPI roomserverAPI.SyncRoomserverAPI,
|
|
|
|
roomID, userID string,
|
|
|
|
limit int,
|
|
|
|
recentEvents []*gomatrixserverlib.HeaderedEvent,
|
|
|
|
) ([]*gomatrixserverlib.HeaderedEvent, error) {
|
|
|
|
// We need to make sure we always include the latest states events, if they are in the timeline.
|
|
|
|
// We grep at least limit * 2 events, to ensure we really get the needed events.
|
|
|
|
stateEvents, err := db.CurrentState(ctx, roomID, &gomatrixserverlib.StateFilter{Limit: limit * 2}, nil)
|
|
|
|
if err != nil {
|
|
|
|
// Not a fatal error, we can continue without the stateEvents,
|
|
|
|
// they are only needed if there are state events in the timeline.
|
|
|
|
logrus.WithError(err).Warnf("failed to get current room state")
|
|
|
|
}
|
|
|
|
alwaysIncludeIDs := make(map[string]struct{}, len(stateEvents))
|
|
|
|
for _, ev := range stateEvents {
|
|
|
|
alwaysIncludeIDs[ev.EventID()] = struct{}{}
|
|
|
|
}
|
|
|
|
startTime := time.Now()
|
|
|
|
events, err := internal.ApplyHistoryVisibilityFilter(ctx, db, rsAPI, recentEvents, alwaysIncludeIDs, userID, "sync")
|
|
|
|
if err != nil {
|
|
|
|
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"duration": time.Since(startTime),
|
|
|
|
"room_id": roomID,
|
2022-08-25 14:42:47 +02:00
|
|
|
"before": len(recentEvents),
|
|
|
|
"after": len(events),
|
2022-08-11 18:23:35 +02:00
|
|
|
}).Debug("applied history visibility (sync)")
|
|
|
|
return events, nil
|
|
|
|
}
|
|
|
|
|
2022-04-26 10:53:17 +02:00
|
|
|
func (p *PDUStreamProvider) addRoomSummary(ctx context.Context, jr *types.JoinResponse, roomID, userID string, latestPosition types.StreamPosition) {
|
|
|
|
// Work out how many members are in the room.
|
|
|
|
joinedCount, _ := p.DB.MembershipCount(ctx, roomID, gomatrixserverlib.Join, latestPosition)
|
|
|
|
invitedCount, _ := p.DB.MembershipCount(ctx, roomID, gomatrixserverlib.Invite, latestPosition)
|
|
|
|
|
|
|
|
jr.Summary.JoinedMemberCount = &joinedCount
|
|
|
|
jr.Summary.InvitedMemberCount = &invitedCount
|
|
|
|
|
|
|
|
fetchStates := []gomatrixserverlib.StateKeyTuple{
|
|
|
|
{EventType: gomatrixserverlib.MRoomName},
|
|
|
|
{EventType: gomatrixserverlib.MRoomCanonicalAlias},
|
|
|
|
}
|
|
|
|
// Check if the room has a name or a canonical alias
|
|
|
|
latestState := &roomserverAPI.QueryLatestEventsAndStateResponse{}
|
|
|
|
err := p.rsAPI.QueryLatestEventsAndState(ctx, &roomserverAPI.QueryLatestEventsAndStateRequest{StateToFetch: fetchStates, RoomID: roomID}, latestState)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Check if the room has a name or canonical alias, if so, return.
|
|
|
|
for _, ev := range latestState.StateEvents {
|
|
|
|
switch ev.Type() {
|
|
|
|
case gomatrixserverlib.MRoomName:
|
|
|
|
if gjson.GetBytes(ev.Content(), "name").Str != "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
case gomatrixserverlib.MRoomCanonicalAlias:
|
|
|
|
if gjson.GetBytes(ev.Content(), "alias").Str != "" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
heroes, err := p.DB.GetRoomHeroes(ctx, roomID, userID, []string{"join", "invite"})
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
sort.Strings(heroes)
|
|
|
|
jr.Summary.Heroes = heroes
|
|
|
|
}
|
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
func (p *PDUStreamProvider) getJoinResponseForCompleteSync(
|
|
|
|
ctx context.Context,
|
|
|
|
roomID string,
|
|
|
|
r types.Range,
|
|
|
|
stateFilter *gomatrixserverlib.StateFilter,
|
2021-01-19 19:00:42 +01:00
|
|
|
eventFilter *gomatrixserverlib.RoomEventFilter,
|
2021-02-04 13:20:37 +01:00
|
|
|
wantFullState bool,
|
2021-01-19 19:00:42 +01:00
|
|
|
device *userapi.Device,
|
2022-08-11 18:23:35 +02:00
|
|
|
isPeek bool,
|
2021-01-08 17:59:06 +01:00
|
|
|
) (jr *types.JoinResponse, err error) {
|
2022-04-20 17:51:37 +02:00
|
|
|
jr = types.NewJoinResponse()
|
2021-01-08 17:59:06 +01:00
|
|
|
// TODO: When filters are added, we may need to call this multiple times to get enough events.
|
|
|
|
// See: https://github.com/matrix-org/synapse/blob/v0.19.3/synapse/handlers/sync.py#L316
|
2021-02-04 13:20:37 +01:00
|
|
|
recentStreamEvents, limited, err := p.DB.RecentEvents(
|
2021-01-19 19:00:42 +01:00
|
|
|
ctx, roomID, r, eventFilter, true, true,
|
2021-01-08 17:59:06 +01:00
|
|
|
)
|
|
|
|
if err != nil {
|
2022-04-20 17:51:37 +02:00
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return jr, nil
|
|
|
|
}
|
2021-01-08 17:59:06 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-03-16 11:18:08 +01:00
|
|
|
// Work our way through the timeline events and pick out the event IDs
|
|
|
|
// of any state events that appear in the timeline. We'll specifically
|
|
|
|
// exclude them at the next step, so that we don't get duplicate state
|
|
|
|
// events in both `recentStreamEvents` and `stateEvents`.
|
|
|
|
var excludingEventIDs []string
|
|
|
|
if !wantFullState {
|
|
|
|
excludingEventIDs = make([]string, 0, len(recentStreamEvents))
|
|
|
|
for _, event := range recentStreamEvents {
|
|
|
|
if event.StateKey() != nil {
|
|
|
|
excludingEventIDs = append(excludingEventIDs, event.EventID())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
stateEvents, err := p.DB.CurrentState(ctx, roomID, stateFilter, excludingEventIDs)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
// Retrieve the backward topology position, i.e. the position of the
|
|
|
|
// oldest event in the room's topology.
|
|
|
|
var prevBatch *types.TopologyToken
|
|
|
|
if len(recentStreamEvents) > 0 {
|
|
|
|
var backwardTopologyPos, backwardStreamPos types.StreamPosition
|
|
|
|
backwardTopologyPos, backwardStreamPos, err = p.DB.PositionInTopology(ctx, recentStreamEvents[0].EventID())
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
prevBatch = &types.TopologyToken{
|
|
|
|
Depth: backwardTopologyPos,
|
|
|
|
PDUPosition: backwardStreamPos,
|
|
|
|
}
|
|
|
|
prevBatch.Decrement()
|
|
|
|
}
|
|
|
|
|
2022-04-26 10:53:17 +02:00
|
|
|
p.addRoomSummary(ctx, jr, roomID, device.UserID, r.From)
|
2022-04-01 17:14:38 +02:00
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
// We don't include a device here as we don't need to send down
|
|
|
|
// transaction IDs for complete syncs, but we do it anyway because Sytest demands it for:
|
|
|
|
// "Can sync a room with a message with a transaction id" - which does a complete sync to check.
|
|
|
|
recentEvents := p.DB.StreamEventsToEvents(device, recentStreamEvents)
|
|
|
|
stateEvents = removeDuplicates(stateEvents, recentEvents)
|
2022-04-19 10:46:45 +02:00
|
|
|
|
2022-08-11 18:23:35 +02:00
|
|
|
events := recentEvents
|
|
|
|
// Only apply history visibility checks if the response is for joined rooms
|
|
|
|
if !isPeek {
|
|
|
|
events, err = applyHistoryVisibilityFilter(ctx, p.DB, p.rsAPI, roomID, device.UserID, eventFilter.Limit, recentEvents)
|
|
|
|
if err != nil {
|
|
|
|
logrus.WithError(err).Error("unable to apply history visibility filter")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we are limited by the filter AND the history visibility filter
|
|
|
|
// didn't "remove" events, return that the response is limited.
|
|
|
|
limited = limited && len(events) == len(recentEvents)
|
|
|
|
|
2022-04-19 10:46:45 +02:00
|
|
|
if stateFilter.LazyLoadMembers {
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
stateEvents, err = p.lazyLoadMembers(ctx, roomID,
|
2022-08-30 14:18:47 +02:00
|
|
|
false, limited, stateFilter,
|
2022-04-19 10:46:45 +02:00
|
|
|
device, recentEvents, stateEvents,
|
|
|
|
)
|
2022-04-20 17:51:37 +02:00
|
|
|
if err != nil && err != sql.ErrNoRows {
|
2022-04-19 10:46:45 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
jr.Timeline.PrevBatch = prevBatch
|
2022-08-11 18:23:35 +02:00
|
|
|
jr.Timeline.Events = gomatrixserverlib.HeaderedToClientEvents(events, gomatrixserverlib.FormatSync)
|
|
|
|
// If we are limited by the filter AND the history visibility filter
|
|
|
|
// didn't "remove" events, return that the response is limited.
|
|
|
|
jr.Timeline.Limited = limited && len(events) == len(recentEvents)
|
2021-01-08 17:59:06 +01:00
|
|
|
jr.State.Events = gomatrixserverlib.HeaderedToClientEvents(stateEvents, gomatrixserverlib.FormatSync)
|
|
|
|
return jr, nil
|
|
|
|
}
|
|
|
|
|
2022-04-19 10:46:45 +02:00
|
|
|
func (p *PDUStreamProvider) lazyLoadMembers(
|
|
|
|
ctx context.Context, roomID string,
|
2022-08-30 14:18:47 +02:00
|
|
|
incremental, limited bool, stateFilter *gomatrixserverlib.StateFilter,
|
2022-04-19 10:46:45 +02:00
|
|
|
device *userapi.Device,
|
|
|
|
timelineEvents, stateEvents []*gomatrixserverlib.HeaderedEvent,
|
|
|
|
) ([]*gomatrixserverlib.HeaderedEvent, error) {
|
|
|
|
if len(timelineEvents) == 0 {
|
|
|
|
return stateEvents, nil
|
|
|
|
}
|
|
|
|
// Work out which memberships to include
|
|
|
|
timelineUsers := make(map[string]struct{})
|
|
|
|
if !incremental {
|
|
|
|
timelineUsers[device.UserID] = struct{}{}
|
|
|
|
}
|
|
|
|
// Add all users the client doesn't know about yet to a list
|
|
|
|
for _, event := range timelineEvents {
|
|
|
|
// Membership is not yet cached, add it to the list
|
|
|
|
if _, ok := p.lazyLoadCache.IsLazyLoadedUserCached(device, roomID, event.Sender()); !ok {
|
|
|
|
timelineUsers[event.Sender()] = struct{}{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Preallocate with the same amount, even if it will end up with fewer values
|
|
|
|
newStateEvents := make([]*gomatrixserverlib.HeaderedEvent, 0, len(stateEvents))
|
|
|
|
// Remove existing membership events we don't care about, e.g. users not in the timeline.events
|
|
|
|
for _, event := range stateEvents {
|
|
|
|
if event.Type() == gomatrixserverlib.MRoomMember && event.StateKey() != nil {
|
|
|
|
// If this is a gapped incremental sync, we still want this membership
|
|
|
|
isGappedIncremental := limited && incremental
|
|
|
|
// We want this users membership event, keep it in the list
|
2022-08-16 15:42:00 +02:00
|
|
|
stateKey := *event.StateKey()
|
|
|
|
if _, ok := timelineUsers[stateKey]; ok || isGappedIncremental {
|
2022-04-19 10:46:45 +02:00
|
|
|
newStateEvents = append(newStateEvents, event)
|
2022-08-30 14:18:47 +02:00
|
|
|
if !stateFilter.IncludeRedundantMembers {
|
2022-08-16 15:42:00 +02:00
|
|
|
p.lazyLoadCache.StoreLazyLoadedUser(device, roomID, stateKey, event.EventID())
|
2022-04-19 10:46:45 +02:00
|
|
|
}
|
2022-08-16 15:42:00 +02:00
|
|
|
delete(timelineUsers, stateKey)
|
2022-04-19 10:46:45 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
newStateEvents = append(newStateEvents, event)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
wantUsers := make([]string, 0, len(timelineUsers))
|
|
|
|
for userID := range timelineUsers {
|
|
|
|
wantUsers = append(wantUsers, userID)
|
|
|
|
}
|
|
|
|
// Query missing membership events
|
2022-08-16 15:42:00 +02:00
|
|
|
filter := gomatrixserverlib.DefaultStateFilter()
|
2022-08-30 14:18:47 +02:00
|
|
|
filter.Limit = stateFilter.Limit
|
2022-08-16 15:42:00 +02:00
|
|
|
filter.Senders = &wantUsers
|
|
|
|
filter.Types = &[]string{gomatrixserverlib.MRoomMember}
|
|
|
|
memberships, err := p.DB.GetStateEventsForRoom(ctx, roomID, &filter)
|
2022-04-19 10:46:45 +02:00
|
|
|
if err != nil {
|
|
|
|
return stateEvents, err
|
|
|
|
}
|
|
|
|
// cache the membership events
|
|
|
|
for _, membership := range memberships {
|
2022-08-16 15:42:00 +02:00
|
|
|
p.lazyLoadCache.StoreLazyLoadedUser(device, roomID, *membership.StateKey(), membership.EventID())
|
2022-04-19 10:46:45 +02:00
|
|
|
}
|
|
|
|
stateEvents = append(newStateEvents, memberships...)
|
|
|
|
return stateEvents, nil
|
|
|
|
}
|
|
|
|
|
2022-04-07 16:08:19 +02:00
|
|
|
// addIgnoredUsersToFilter adds ignored users to the eventfilter and
|
|
|
|
// the syncreq itself for further use in streams.
|
|
|
|
func (p *PDUStreamProvider) addIgnoredUsersToFilter(ctx context.Context, req *types.SyncRequest, eventFilter *gomatrixserverlib.RoomEventFilter) error {
|
|
|
|
ignores, err := p.DB.IgnoresForUser(ctx, req.Device.UserID)
|
|
|
|
if err != nil {
|
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
req.IgnoredUsers = *ignores
|
2022-04-11 09:05:23 +02:00
|
|
|
userList := make([]string, 0, len(ignores.List))
|
2022-04-07 16:08:19 +02:00
|
|
|
for userID := range ignores.List {
|
2022-04-11 09:05:23 +02:00
|
|
|
userList = append(userList, userID)
|
|
|
|
}
|
|
|
|
if len(userList) > 0 {
|
|
|
|
eventFilter.NotSenders = &userList
|
2022-04-07 16:08:19 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-01-08 17:59:06 +01:00
|
|
|
func removeDuplicates(stateEvents, recentEvents []*gomatrixserverlib.HeaderedEvent) []*gomatrixserverlib.HeaderedEvent {
|
|
|
|
for _, recentEv := range recentEvents {
|
|
|
|
if recentEv.StateKey() == nil {
|
|
|
|
continue // not a state event
|
|
|
|
}
|
|
|
|
// TODO: This is a linear scan over all the current state events in this room. This will
|
|
|
|
// be slow for big rooms. We should instead sort the state events by event ID (ORDER BY)
|
|
|
|
// then do a binary search to find matching events, similar to what roomserver does.
|
|
|
|
for j := 0; j < len(stateEvents); j++ {
|
|
|
|
if stateEvents[j].EventID() == recentEv.EventID() {
|
|
|
|
// overwrite the element to remove with the last element then pop the last element.
|
|
|
|
// This is orders of magnitude faster than re-slicing, but doesn't preserve ordering
|
|
|
|
// (we don't care about the order of stateEvents)
|
|
|
|
stateEvents[j] = stateEvents[len(stateEvents)-1]
|
|
|
|
stateEvents = stateEvents[:len(stateEvents)-1]
|
|
|
|
break // there shouldn't be multiple events with the same event ID
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return stateEvents
|
|
|
|
}
|