about summary refs log tree commit diff
path: root/Tests/LibMatrix.HomeserverEmulator/Controllers/SyncController.cs
blob: 024d07165cbb4f372b16f99b3f46bc91492c67b2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using ArcaneLibs.Extensions;
using LibMatrix.EventTypes.Spec.State;
using LibMatrix.HomeserverEmulator.Extensions;
using LibMatrix.HomeserverEmulator.Services;
using LibMatrix.Responses;
using Microsoft.AspNetCore.Mvc;

namespace LibMatrix.HomeserverEmulator.Controllers;

[ApiController]
[Route("/_matrix/client/{version}/")]
public class SyncController(ILogger<SyncController> logger, TokenService tokenService, UserStore userStore, RoomStore roomStore, HSEConfiguration cfg) : ControllerBase {
    [HttpGet("sync")]
    [SuppressMessage("ReSharper.DPA", "DPA0011: High execution time of MVC action", Justification = "Endpoint is expected to wait until data is available or timeout.")]
    public async Task<SyncResponse> Sync([FromQuery] string? since = null, [FromQuery] int? timeout = 5000) {
        var sw = Stopwatch.StartNew();
        var token = tokenService.GetAccessToken(HttpContext);

        var user = await userStore.GetUserByToken(token);
        if (user == null)
            throw new MatrixException() {
                ErrorCode = "M_UNKNOWN_TOKEN",
                Error = "No such user"
            };
        var session = user.AccessTokens[token];
        UserStore.User.SessionInfo.UserSyncState newSyncState = new();

        SyncResponse syncResp;
        if (string.IsNullOrWhiteSpace(since) || !session.SyncStates.ContainsKey(since))
            syncResp = InitialSync(user, session);
        else {
            var syncState = session.SyncStates[since];
            newSyncState = syncState.Clone();

            var newSyncToken = Guid.NewGuid().ToString();
            do {
                syncResp = IncrementalSync(user, session, syncState);
                syncResp.NextBatch = newSyncToken;
            } while (!await HasDataOrStall(syncResp) && sw.ElapsedMilliseconds < timeout);

            if (sw.ElapsedMilliseconds > timeout) {
                logger.LogTrace("Sync timed out after {Elapsed}", sw.Elapsed);
                return new() {
                    NextBatch = since
                };
            }
        }

        session.SyncStates[syncResp.NextBatch] = RecalculateSyncStates(newSyncState, syncResp);
        logger.LogTrace("Responding to sync after {totalElapsed}", sw.Elapsed);
        return syncResp;
    }

    private UserStore.User.SessionInfo.UserSyncState RecalculateSyncStates(UserStore.User.SessionInfo.UserSyncState newSyncState, SyncResponse sync) {
        logger.LogTrace("Updating sync state");
        var syncStateRecalcSw = Stopwatch.StartNew();
        foreach (var (roomId, roomData) in sync.Rooms?.Join ?? []) {
            if (!newSyncState.RoomPositions.ContainsKey(roomId))
                newSyncState.RoomPositions[roomId] = new();
            var state = newSyncState.RoomPositions[roomId];

            state.TimelinePosition += roomData.Timeline?.Events?.Count ?? 0;
            state.LastTimelineEventId = roomData.Timeline?.Events?.LastOrDefault()?.EventId ?? state.LastTimelineEventId;
            state.AccountDataPosition += roomData.AccountData?.Events?.Count ?? 0;
            state.Joined = true;
        }

        foreach (var (roomId, _) in sync.Rooms?.Invite ?? []) {
            if (!newSyncState.RoomPositions.ContainsKey(roomId))
                newSyncState.RoomPositions[roomId] = new() {
                    Joined = false
                };
        }

        foreach (var (roomId, _) in sync.Rooms?.Leave ?? []) {
            if (newSyncState.RoomPositions.ContainsKey(roomId))
                newSyncState.RoomPositions.Remove(roomId);
        }

        logger.LogTrace("Updated sync state in {Elapsed}", syncStateRecalcSw.Elapsed);

        return newSyncState;
    }

#region Initial Sync parts

    private SyncResponse InitialSync(UserStore.User user, UserStore.User.SessionInfo session) {
        var response = new SyncResponse() {
            NextBatch = Guid.NewGuid().ToString(),
            DeviceOneTimeKeysCount = new(),
            AccountData = new(events: user.AccountData.ToList())
        };

        session.SyncStates.Add(response.NextBatch, new());

        var rooms = roomStore._rooms.Where(x => x.State.Any(y => y.Type == "m.room.member" && y.StateKey == user.UserId)).ToList();
        foreach (var room in rooms) {
            response.Rooms ??= new();
            response.Rooms.Join ??= new();

            response.Rooms.Join[room.RoomId] = new() {
                State = new(room.State.ToList()),
                Timeline = new(events: room.Timeline.ToList(), limited: false),
                AccountData = new(room.AccountData.GetOrCreate(user.UserId, _ => []).ToList())
            };
        }

        return response;
    }

    private SyncResponse.RoomsDataStructure.JoinedRoomDataStructure GetInitialSyncRoomData(RoomStore.Room room, UserStore.User user) {
        return new() {
            State = new(room.State.ToList()),
            Timeline = new(room.Timeline.ToList(), false),
            AccountData = new(room.AccountData.GetOrCreate(user.UserId, _ => []).ToList())
        };
    }

#endregion

    private SyncResponse IncrementalSync(UserStore.User user, UserStore.User.SessionInfo session, UserStore.User.SessionInfo.UserSyncState syncState) {
        return new SyncResponse {
            Rooms = GetIncrementalSyncRooms(user, session, syncState)
        };
    }

#region Incremental Sync parts

    private SyncResponse.RoomsDataStructure GetIncrementalSyncRooms(UserStore.User user, UserStore.User.SessionInfo session, UserStore.User.SessionInfo.UserSyncState syncState) {
        SyncResponse.RoomsDataStructure data = new() {
            Join = [],
            Invite = [],
            Leave = []
        };

        // step 1: check previously synced rooms
        foreach (var (roomId, roomPosition) in syncState.RoomPositions) {
            var room = roomStore.GetRoomById(roomId);
            if (room == null) {
                // room no longer exists
                data.Leave[roomId] = new();
                continue;
            }

            if (roomPosition.Joined) {
                var newTimelineEvents = room.Timeline.Skip(roomPosition.TimelinePosition).ToList();
                var newAccountDataEvents = room.AccountData[user.UserId].Skip(roomPosition.AccountDataPosition).ToList();
                if (newTimelineEvents.Count == 0 && newAccountDataEvents.Count == 0) continue;
                data.Join[room.RoomId] = new() {
                    State = new(newTimelineEvents.GetCalculatedState()),
                    Timeline = new(newTimelineEvents, false)
                };
            }
        }

        if (data.Join.Count > 0) return data;

        // step 2: check newly joined rooms
        var untrackedRooms = roomStore._rooms.Where(r => !syncState.RoomPositions.ContainsKey(r.RoomId)).ToList();

        var allJoinedRooms = roomStore.GetRoomsByMember(user.UserId).ToArray();
        if (allJoinedRooms.Length == 0) return data;
        var rooms = Random.Shared.GetItems(allJoinedRooms, Math.Min(allJoinedRooms.Length, 50));
        foreach (var membership in rooms) {
            var membershipContent = membership.TypedContent as RoomMemberEventContent ??
                                    throw new InvalidOperationException("Membership event content is not RoomMemberEventContent");
            var room = roomStore.GetRoomById(membership.RoomId!);
            //handle leave
            if (syncState.RoomPositions.TryGetValue(membership.RoomId!, out var syncPosition)) {
                // logger.LogTrace("Found sync position {roomId} {value}", room.RoomId, syncPosition.ToJson(indent: false, ignoreNull: false));

                if (membershipContent.Membership == "join") {
                    var newTimelineEvents = room.Timeline.Skip(syncPosition.TimelinePosition).ToList();
                    var newAccountDataEvents = room.AccountData[user.UserId].Skip(syncPosition.AccountDataPosition).ToList();
                    if (newTimelineEvents.Count == 0 && newAccountDataEvents.Count == 0) continue;
                    data.Join[room.RoomId] = new() {
                        State = new(newTimelineEvents.GetCalculatedState()),
                        Timeline = new(newTimelineEvents, false)
                    };
                }
            }
            else {
                //syncPosisition = null
                if (membershipContent.Membership == "join") {
                    var joinData = data.Join[membership.RoomId!] = new() {
                        State = new(room.State.ToList()),
                        Timeline = new(events: room.Timeline.ToList(), limited: false),
                        AccountData = new(room.AccountData.GetOrCreate(user.UserId, _ => []).ToList())
                    };
                }
            }
        }

        //handle nonexistant rooms
        foreach (var roomId in syncState.RoomPositions.Keys) {
            if (!roomStore._rooms.Any(x => x.RoomId == roomId)) {
                data.Leave[roomId] = new();
                session.SyncStates[session.SyncStates.Last().Key].RoomPositions.Remove(roomId);
            }
        }

        return data;
    }

#endregion

    private async Task<bool> HasDataOrStall(SyncResponse resp) {
        // logger.LogTrace("Checking if sync response has data: {resp}", resp.ToJson(indent: false, ignoreNull: true));
        // if (resp.AccountData?.Events?.Count > 0) return true;
        // if (resp.Rooms?.Invite?.Count > 0) return true;
        // if (resp.Rooms?.Join?.Count > 0) return true;
        // if (resp.Rooms?.Leave?.Count > 0) return true;
        // if (resp.Presence?.Events?.Count > 0) return true;
        // if (resp.DeviceLists?.Changed?.Count > 0) return true;
        // if (resp.DeviceLists?.Left?.Count > 0) return true;
        // if (resp.ToDevice?.Events?.Count > 0) return true;
        //
        // var hasData =
        //     resp is not {
        //         AccountData: null or {
        //             Events: null or { Count: 0 }
        //         },
        //         Rooms: null or {
        //             Invite: null or { Count: 0 },
        //             Join: null or { Count: 0 },
        //             Leave: null or { Count: 0 }
        //         },
        //         Presence: null or {
        //             Events: null or { Count: 0 }
        //         },
        //         DeviceLists: null or {
        //             Changed: null or { Count: 0 },
        //             Left: null or { Count: 0 }
        //         },
        //         ToDevice: null or {
        //             Events: null or { Count: 0 }
        //         }
        //     };

        var hasData = resp is {
            AccountData: {
                Events: { Count: > 0 }
            }
        } or {
            Presence: {
                Events: { Count: > 0 }
            }
        } or {
            DeviceLists: {
                Changed: { Count: > 0 },
                Left: { Count: > 0 }
            }
        } or {
            ToDevice: {
                Events: { Count: > 0 }
            }
        };

        if (!hasData) {
            // hasData = 
        }

        if (!hasData) {
            // logger.LogDebug($"Sync response has no data, stalling for 1000ms: {resp.ToJson(indent: false, ignoreNull: true)}");
            await Task.Delay(10);
        }

        return hasData;
    }
}