File: test_extension_thread_subscriptions.py

package info (click to toggle)
matrix-synapse 1.143.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 79,852 kB
  • sloc: python: 258,912; javascript: 7,330; sql: 4,733; sh: 1,281; perl: 626; makefile: 207
file content (497 lines) | stat: -rw-r--r-- 17,123 bytes parent folder | download | duplicates (2)
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
#
# This file is licensed under the Affero General Public License (AGPL) version 3.
#
# Copyright (C) 2025 New Vector, Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# See the GNU Affero General Public License for more details:
# <https://www.gnu.org/licenses/agpl-3.0.html>.
#
import logging
from http import HTTPStatus
from typing import cast

from twisted.test.proto_helpers import MemoryReactor

import synapse.rest.admin
from synapse.rest.client import login, room, sync, thread_subscriptions
from synapse.server import HomeServer
from synapse.types import JsonDict
from synapse.util.clock import Clock

from tests.rest.client.sliding_sync.test_sliding_sync import SlidingSyncBase

logger = logging.getLogger(__name__)


# The name of the extension. Currently unstable-prefixed.
EXT_NAME = "io.element.msc4308.thread_subscriptions"


class SlidingSyncThreadSubscriptionsExtensionTestCase(SlidingSyncBase):
    """
    Test the thread subscriptions extension in the Sliding Sync API.
    """

    maxDiff = None

    servlets = [
        synapse.rest.admin.register_servlets,
        login.register_servlets,
        room.register_servlets,
        sync.register_servlets,
        thread_subscriptions.register_servlets,
    ]

    def default_config(self) -> JsonDict:
        config = super().default_config()
        config["experimental_features"] = {"msc4306_enabled": True}
        return config

    def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
        self.store = hs.get_datastores().main
        self.storage_controllers = hs.get_storage_controllers()
        super().prepare(reactor, clock, hs)

    def test_no_data_initial_sync(self) -> None:
        """
        Test enabling thread subscriptions extension during initial sync with no data.
        """
        user1_id = self.register_user("user1", "pass")
        user1_tok = self.login(user1_id, "pass")
        sync_body = {
            "lists": {},
            "extensions": {
                EXT_NAME: {
                    "enabled": True,
                }
            },
        }

        # Sync
        response_body, _ = self.do_sync(sync_body, tok=user1_tok)

        # Assert
        self.assertNotIn(EXT_NAME, response_body["extensions"])

    def test_no_data_incremental_sync(self) -> None:
        """
        Test enabling thread subscriptions extension during incremental sync with no data.
        """
        user1_id = self.register_user("user1", "pass")
        user1_tok = self.login(user1_id, "pass")
        initial_sync_body: JsonDict = {
            "lists": {},
        }

        # Initial sync
        response_body, sync_pos = self.do_sync(initial_sync_body, tok=user1_tok)

        # Incremental sync with extension enabled
        sync_body = {
            "lists": {},
            "extensions": {
                EXT_NAME: {
                    "enabled": True,
                }
            },
        }
        response_body, _ = self.do_sync(sync_body, tok=user1_tok, since=sync_pos)

        # Assert
        self.assertNotIn(
            EXT_NAME,
            response_body["extensions"],
            response_body,
        )

    def test_thread_subscription_initial_sync(self) -> None:
        """
        Test thread subscriptions appear in initial sync response.
        """
        user1_id = self.register_user("user1", "pass")
        user1_tok = self.login(user1_id, "pass")
        room_id = self.helper.create_room_as(user1_id, tok=user1_tok)
        thread_root_resp = self.helper.send(room_id, body="Thread root", tok=user1_tok)
        thread_root_id = thread_root_resp["event_id"]

        # get the baseline stream_id of the thread_subscriptions stream
        # before we write any data.
        # Required because the initial value differs between SQLite and Postgres.
        base = self.store.get_max_thread_subscriptions_stream_id()

        self._subscribe_to_thread(user1_id, room_id, thread_root_id)
        sync_body = {
            "lists": {},
            "extensions": {
                EXT_NAME: {
                    "enabled": True,
                }
            },
        }

        # Sync
        response_body, _ = self.do_sync(sync_body, tok=user1_tok)

        # Assert
        self.assertEqual(
            response_body["extensions"][EXT_NAME],
            {
                "subscribed": {
                    room_id: {
                        thread_root_id: {
                            "automatic": False,
                            "bump_stamp": base + 1,
                        }
                    }
                }
            },
        )

    def test_thread_subscription_incremental_sync(self) -> None:
        """
        Test new thread subscriptions appear in incremental sync response.
        """
        user1_id = self.register_user("user1", "pass")
        user1_tok = self.login(user1_id, "pass")
        room_id = self.helper.create_room_as(user1_id, tok=user1_tok)
        sync_body = {
            "lists": {},
            "extensions": {
                EXT_NAME: {
                    "enabled": True,
                }
            },
        }
        thread_root_resp = self.helper.send(room_id, body="Thread root", tok=user1_tok)
        thread_root_id = thread_root_resp["event_id"]

        # get the baseline stream_id of the thread_subscriptions stream
        # before we write any data.
        # Required because the initial value differs between SQLite and Postgres.
        base = self.store.get_max_thread_subscriptions_stream_id()

        # Initial sync
        _, sync_pos = self.do_sync(sync_body, tok=user1_tok)
        logger.info("Synced to: %r, now subscribing to thread", sync_pos)

        # Subscribe
        self._subscribe_to_thread(user1_id, room_id, thread_root_id)

        # Incremental sync
        response_body, sync_pos = self.do_sync(sync_body, tok=user1_tok, since=sync_pos)
        logger.info("Synced to: %r", sync_pos)

        # Assert
        self.assertEqual(
            response_body["extensions"][EXT_NAME],
            {
                "subscribed": {
                    room_id: {
                        thread_root_id: {
                            "automatic": False,
                            "bump_stamp": base + 1,
                        }
                    }
                }
            },
        )

    def test_unsubscribe_from_thread(self) -> None:
        """
        Test unsubscribing from a thread.
        """
        user1_id = self.register_user("user1", "pass")
        user1_tok = self.login(user1_id, "pass")
        room_id = self.helper.create_room_as(user1_id, tok=user1_tok)
        thread_root_resp = self.helper.send(room_id, body="Thread root", tok=user1_tok)
        thread_root_id = thread_root_resp["event_id"]

        # get the baseline stream_id of the thread_subscriptions stream
        # before we write any data.
        # Required because the initial value differs between SQLite and Postgres.
        base = self.store.get_max_thread_subscriptions_stream_id()

        self._subscribe_to_thread(user1_id, room_id, thread_root_id)
        sync_body = {
            "lists": {},
            "extensions": {
                EXT_NAME: {
                    "enabled": True,
                }
            },
        }

        response_body, sync_pos = self.do_sync(sync_body, tok=user1_tok)

        # Assert: Subscription present
        self.assertIn(EXT_NAME, response_body["extensions"])
        self.assertEqual(
            response_body["extensions"][EXT_NAME],
            {
                "subscribed": {
                    room_id: {
                        thread_root_id: {"automatic": False, "bump_stamp": base + 1}
                    }
                }
            },
        )

        # Unsubscribe
        self._unsubscribe_from_thread(user1_id, room_id, thread_root_id)

        # Incremental sync
        response_body, sync_pos = self.do_sync(sync_body, tok=user1_tok, since=sync_pos)

        # Assert: Unsubscription present
        self.assertEqual(
            response_body["extensions"][EXT_NAME],
            {"unsubscribed": {room_id: {thread_root_id: {"bump_stamp": base + 2}}}},
        )

    def test_multiple_thread_subscriptions(self) -> None:
        """
        Test handling of multiple thread subscriptions.
        """
        user1_id = self.register_user("user1", "pass")
        user1_tok = self.login(user1_id, "pass")
        room_id = self.helper.create_room_as(user1_id, tok=user1_tok)

        # Create thread roots
        thread_root_resp1 = self.helper.send(
            room_id, body="Thread root 1", tok=user1_tok
        )
        thread_root_id1 = thread_root_resp1["event_id"]
        thread_root_resp2 = self.helper.send(
            room_id, body="Thread root 2", tok=user1_tok
        )
        thread_root_id2 = thread_root_resp2["event_id"]
        thread_root_resp3 = self.helper.send(
            room_id, body="Thread root 3", tok=user1_tok
        )
        thread_root_id3 = thread_root_resp3["event_id"]

        # get the baseline stream_id of the thread_subscriptions stream
        # before we write any data.
        # Required because the initial value differs between SQLite and Postgres.
        base = self.store.get_max_thread_subscriptions_stream_id()

        # Subscribe to threads
        self._subscribe_to_thread(user1_id, room_id, thread_root_id1)
        self._subscribe_to_thread(user1_id, room_id, thread_root_id2)
        self._subscribe_to_thread(user1_id, room_id, thread_root_id3)

        sync_body = {
            "lists": {},
            "extensions": {
                EXT_NAME: {
                    "enabled": True,
                }
            },
        }

        # Sync
        response_body, _ = self.do_sync(sync_body, tok=user1_tok)

        # Assert
        self.assertEqual(
            response_body["extensions"][EXT_NAME],
            {
                "subscribed": {
                    room_id: {
                        thread_root_id1: {
                            "automatic": False,
                            "bump_stamp": base + 1,
                        },
                        thread_root_id2: {
                            "automatic": False,
                            "bump_stamp": base + 2,
                        },
                        thread_root_id3: {
                            "automatic": False,
                            "bump_stamp": base + 3,
                        },
                    }
                }
            },
        )

    def test_limit_parameter(self) -> None:
        """
        Test limit parameter in thread subscriptions extension.
        """
        user1_id = self.register_user("user1", "pass")
        user1_tok = self.login(user1_id, "pass")
        room_id = self.helper.create_room_as(user1_id, tok=user1_tok)

        # Create 5 thread roots and subscribe to each
        thread_root_ids = []
        for i in range(5):
            thread_root_resp = self.helper.send(
                room_id, body=f"Thread root {i}", tok=user1_tok
            )
            thread_root_ids.append(thread_root_resp["event_id"])
            self._subscribe_to_thread(user1_id, room_id, thread_root_ids[-1])

        sync_body = {
            "lists": {},
            "extensions": {EXT_NAME: {"enabled": True, "limit": 3}},
        }

        # Sync
        response_body, _ = self.do_sync(sync_body, tok=user1_tok)

        # Assert
        thread_subscriptions = response_body["extensions"][EXT_NAME]
        self.assertEqual(
            len(thread_subscriptions["subscribed"][room_id]), 3, thread_subscriptions
        )

    def test_limit_and_companion_backpagination(self) -> None:
        """
        Create 1 thread subscription, do a sync, create 4 more,
        then sync with a limit of 2 and fill in the gap
        using the companion /thread_subscriptions endpoint.
        """

        thread_root_ids: list[str] = []

        def make_subscription() -> None:
            thread_root_resp = self.helper.send(
                room_id, body="Some thread root", tok=user1_tok
            )
            thread_root_ids.append(thread_root_resp["event_id"])
            self._subscribe_to_thread(user1_id, room_id, thread_root_ids[-1])

        user1_id = self.register_user("user1", "pass")
        user1_tok = self.login(user1_id, "pass")
        room_id = self.helper.create_room_as(user1_id, tok=user1_tok)

        # get the baseline stream_id of the thread_subscriptions stream
        # before we write any data.
        # Required because the initial value differs between SQLite and Postgres.
        base = self.store.get_max_thread_subscriptions_stream_id()

        # Make our first subscription
        make_subscription()

        # Sync for the first time
        sync_body = {
            "lists": {},
            "extensions": {EXT_NAME: {"enabled": True, "limit": 2}},
        }

        sync_resp, first_sync_pos = self.do_sync(sync_body, tok=user1_tok)

        thread_subscriptions = sync_resp["extensions"][EXT_NAME]
        self.assertEqual(
            thread_subscriptions["subscribed"],
            {
                room_id: {
                    thread_root_ids[0]: {"automatic": False, "bump_stamp": base + 1},
                }
            },
        )

        # Get our pos for the next sync
        first_sync_pos = sync_resp["pos"]

        # Create 5 more thread subscriptions and subscribe to each
        for _ in range(5):
            make_subscription()

        # Now sync again. Our limit is 2,
        # so we should get the latest 2 subscriptions,
        # with a gap of 3 more subscriptions in the middle
        sync_resp, _pos = self.do_sync(sync_body, tok=user1_tok, since=first_sync_pos)

        thread_subscriptions = sync_resp["extensions"][EXT_NAME]
        self.assertEqual(
            thread_subscriptions["subscribed"],
            {
                room_id: {
                    thread_root_ids[4]: {"automatic": False, "bump_stamp": base + 5},
                    thread_root_ids[5]: {"automatic": False, "bump_stamp": base + 6},
                }
            },
        )
        # 1st backpagination: expecting a page with 2 subscriptions
        page, end_tok = self._do_backpaginate(
            from_tok=thread_subscriptions["prev_batch"],
            to_tok=first_sync_pos,
            limit=2,
            access_token=user1_tok,
        )
        self.assertIsNotNone(end_tok, "backpagination should continue")
        self.assertEqual(
            page["subscribed"],
            {
                room_id: {
                    thread_root_ids[2]: {"automatic": False, "bump_stamp": base + 3},
                    thread_root_ids[3]: {"automatic": False, "bump_stamp": base + 4},
                }
            },
        )

        # 2nd backpagination: expecting a page with only 1 subscription
        # and no other token for further backpagination
        assert end_tok is not None
        page, end_tok = self._do_backpaginate(
            from_tok=end_tok, to_tok=first_sync_pos, limit=2, access_token=user1_tok
        )
        self.assertIsNone(end_tok, "backpagination should have finished")
        self.assertEqual(
            page["subscribed"],
            {
                room_id: {
                    thread_root_ids[1]: {"automatic": False, "bump_stamp": base + 2},
                }
            },
        )

    def _do_backpaginate(
        self, *, from_tok: str, to_tok: str, limit: int, access_token: str
    ) -> tuple[JsonDict, str | None]:
        channel = self.make_request(
            "GET",
            "/_matrix/client/unstable/io.element.msc4308/thread_subscriptions"
            f"?from={from_tok}&to={to_tok}&limit={limit}&dir=b",
            access_token=access_token,
        )

        self.assertEqual(channel.code, HTTPStatus.OK, channel.json_body)
        body = channel.json_body
        return body, cast(str | None, body.get("end"))

    def _subscribe_to_thread(
        self, user_id: str, room_id: str, thread_root_id: str
    ) -> None:
        """
        Helper method to subscribe a user to a thread.
        """
        self.get_success(
            self.store.subscribe_user_to_thread(
                user_id=user_id,
                room_id=room_id,
                thread_root_event_id=thread_root_id,
                automatic_event_orderings=None,
            )
        )

    def _unsubscribe_from_thread(
        self, user_id: str, room_id: str, thread_root_id: str
    ) -> None:
        """
        Helper method to unsubscribe a user from a thread.
        """
        self.get_success(
            self.store.unsubscribe_user_from_thread(
                user_id=user_id,
                room_id=room_id,
                thread_root_event_id=thread_root_id,
            )
        )