summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--changelog.d/4890.feature1
-rw-r--r--changelog.d/4895.feature1
-rw-r--r--changelog.d/4900.feature1
-rw-r--r--changelog.d/4902.misc1
-rw-r--r--changelog.d/4905.misc1
-rw-r--r--docs/sample_config.yaml13
-rw-r--r--synapse/config/ratelimiting.py12
-rw-r--r--synapse/config/server.py5
-rw-r--r--synapse/config/user_directory.py9
-rw-r--r--synapse/federation/sender/__init__.py115
-rw-r--r--synapse/federation/sender/per_destination_queue.py64
-rw-r--r--synapse/handlers/receipts.py2
-rw-r--r--synapse/replication/tcp/resource.py18
-rw-r--r--synapse/rest/client/v2_alpha/user_directory.py6
-rw-r--r--synapse/storage/user_directory.py13
-rw-r--r--tests/federation/test_federation_sender.py128
-rw-r--r--tests/handlers/test_user_directory.py52
-rw-r--r--tests/server.py9
18 files changed, 420 insertions, 31 deletions
diff --git a/changelog.d/4890.feature b/changelog.d/4890.feature
new file mode 100644
index 0000000000..8d74262250
--- /dev/null
+++ b/changelog.d/4890.feature
@@ -0,0 +1 @@
+Batch up outgoing read-receipts to reduce federation traffic.
diff --git a/changelog.d/4895.feature b/changelog.d/4895.feature
new file mode 100644
index 0000000000..5dd7c68194
--- /dev/null
+++ b/changelog.d/4895.feature
@@ -0,0 +1 @@
+Add option to disable searching the user directory.
diff --git a/changelog.d/4900.feature b/changelog.d/4900.feature
new file mode 100644
index 0000000000..8f792b8890
--- /dev/null
+++ b/changelog.d/4900.feature
@@ -0,0 +1 @@
+The user directory has been rewritten to make it faster, with less chance of falling behind on a large server.
diff --git a/changelog.d/4902.misc b/changelog.d/4902.misc
new file mode 100644
index 0000000000..fecc06a6e8
--- /dev/null
+++ b/changelog.d/4902.misc
@@ -0,0 +1 @@
+Add a config option for torture-testing worker replication.
diff --git a/changelog.d/4905.misc b/changelog.d/4905.misc
new file mode 100644
index 0000000000..0f00d5a3d5
--- /dev/null
+++ b/changelog.d/4905.misc
@@ -0,0 +1 @@
+Log requests which are simulated by the unit tests.
diff --git a/docs/sample_config.yaml b/docs/sample_config.yaml
index d1a419b240..4ada0fba0e 100644
--- a/docs/sample_config.yaml
+++ b/docs/sample_config.yaml
@@ -438,6 +438,14 @@ log_config: "CONFDIR/SERVERNAME.log.config"
 #
 #federation_rc_concurrent: 3
 
+# Target outgoing federation transaction frequency for sending read-receipts,
+# per-room.
+#
+# If we end up trying to send out more read-receipts, they will get buffered up
+# into fewer transactions.
+#
+#federation_rr_transactions_per_room_per_second: 50
+
 
 
 # Directory where uploaded images and attachments are stored.
@@ -954,6 +962,10 @@ password_config:
 
 # User Directory configuration
 #
+# 'enabled' defines whether users can search the user directory. If
+# false then empty responses are returned to all queries. Defaults to
+# true.
+#
 # 'search_all_users' defines whether to search all users visible to your HS
 # when searching the user directory, rather than limiting to users visible
 # in public rooms.  Defaults to false.  If you set it True, you'll have to run
@@ -961,6 +973,7 @@ password_config:
 # on your database to tell it to rebuild the user_directory search indexes.
 #
 #user_directory:
+#  enabled: true
 #  search_all_users: false
 
 
diff --git a/synapse/config/ratelimiting.py b/synapse/config/ratelimiting.py
index 898a19dd8c..5a68399e63 100644
--- a/synapse/config/ratelimiting.py
+++ b/synapse/config/ratelimiting.py
@@ -42,6 +42,10 @@ class RatelimitConfig(Config):
         self.federation_rc_reject_limit = config.get("federation_rc_reject_limit", 50)
         self.federation_rc_concurrent = config.get("federation_rc_concurrent", 3)
 
+        self.federation_rr_transactions_per_room_per_second = config.get(
+            "federation_rr_transactions_per_room_per_second", 50,
+        )
+
     def default_config(self, **kwargs):
         return """\
         ## Ratelimiting ##
@@ -111,4 +115,12 @@ class RatelimitConfig(Config):
         # single server
         #
         #federation_rc_concurrent: 3
+
+        # Target outgoing federation transaction frequency for sending read-receipts,
+        # per-room.
+        #
+        # If we end up trying to send out more read-receipts, they will get buffered up
+        # into fewer transactions.
+        #
+        #federation_rr_transactions_per_room_per_second: 50
         """
diff --git a/synapse/config/server.py b/synapse/config/server.py
index 499eb30bea..08e4e45482 100644
--- a/synapse/config/server.py
+++ b/synapse/config/server.py
@@ -126,6 +126,11 @@ class ServerConfig(Config):
                 self.public_baseurl += '/'
         self.start_pushers = config.get("start_pushers", True)
 
+        # (undocumented) option for torturing the worker-mode replication a bit,
+        # for testing. The value defines the number of milliseconds to pause before
+        # sending out any replication updates.
+        self.replication_torture_level = config.get("replication_torture_level")
+
         self.listeners = []
         for listener in config.get("listeners", []):
             if not isinstance(listener.get("port", None), int):
diff --git a/synapse/config/user_directory.py b/synapse/config/user_directory.py
index fab3a7d1c8..142754a7dc 100644
--- a/synapse/config/user_directory.py
+++ b/synapse/config/user_directory.py
@@ -22,9 +22,13 @@ class UserDirectoryConfig(Config):
     """
 
     def read_config(self, config):
+        self.user_directory_search_enabled = True
         self.user_directory_search_all_users = False
         user_directory_config = config.get("user_directory", None)
         if user_directory_config:
+            self.user_directory_search_enabled = (
+                user_directory_config.get("enabled", True)
+            )
             self.user_directory_search_all_users = (
                 user_directory_config.get("search_all_users", False)
             )
@@ -33,6 +37,10 @@ class UserDirectoryConfig(Config):
         return """
         # User Directory configuration
         #
+        # 'enabled' defines whether users can search the user directory. If
+        # false then empty responses are returned to all queries. Defaults to
+        # true.
+        #
         # 'search_all_users' defines whether to search all users visible to your HS
         # when searching the user directory, rather than limiting to users visible
         # in public rooms.  Defaults to false.  If you set it True, you'll have to run
@@ -40,5 +48,6 @@ class UserDirectoryConfig(Config):
         # on your database to tell it to rebuild the user_directory search indexes.
         #
         #user_directory:
+        #  enabled: true
         #  search_all_users: false
         """
diff --git a/synapse/federation/sender/__init__.py b/synapse/federation/sender/__init__.py
index 1bcc353d18..1dc041752b 100644
--- a/synapse/federation/sender/__init__.py
+++ b/synapse/federation/sender/__init__.py
@@ -104,7 +104,26 @@ class FederationSender(object):
 
         self._processing_pending_presence = False
 
+        # map from room_id to a set of PerDestinationQueues which we believe are
+        # awaiting a call to flush_read_receipts_for_room. The presence of an entry
+        # here for a given room means that we are rate-limiting RR flushes to that room,
+        # and that there is a pending call to _flush_rrs_for_room in the system.
+        self._queues_awaiting_rr_flush_by_room = {
+        }   # type: dict[str, set[PerDestinationQueue]]
+
+        self._rr_txn_interval_per_room_ms = (
+            1000.0 / hs.get_config().federation_rr_transactions_per_room_per_second
+        )
+
     def _get_per_destination_queue(self, destination):
+        """Get or create a PerDestinationQueue for the given destination
+
+        Args:
+            destination (str): server_name of remote server
+
+        Returns:
+            PerDestinationQueue
+        """
         queue = self._per_destination_queues.get(destination)
         if not queue:
             queue = PerDestinationQueue(self.hs, self._transaction_manager, destination)
@@ -250,33 +269,91 @@ class FederationSender(object):
         Args:
             receipt (synapse.types.ReadReceipt): receipt to be sent
         """
+
+        # Some background on the rate-limiting going on here.
+        #
+        # It turns out that if we attempt to send out RRs as soon as we get them from
+        # a client, then we end up trying to do several hundred Hz of federation
+        # transactions. (The number of transactions scales as O(N^2) on the size of a
+        # room, since in a large room we have both more RRs coming in, and more servers
+        # to send them to.)
+        #
+        # This leads to a lot of CPU load, and we end up getting behind. The solution
+        # currently adopted is as follows:
+        #
+        # The first receipt in a given room is sent out immediately, at time T0. Any
+        # further receipts are, in theory, batched up for N seconds, where N is calculated
+        # based on the number of servers in the room to achieve a transaction frequency
+        # of around 50Hz. So, for example, if there were 100 servers in the room, then
+        # N would be 100 / 50Hz = 2 seconds.
+        #
+        # Then, after T+N, we flush out any receipts that have accumulated, and restart
+        # the timer to flush out more receipts at T+2N, etc. If no receipts accumulate,
+        # we stop the cycle and go back to the start.
+        #
+        # However, in practice, it is often possible to flush out receipts earlier: in
+        # particular, if we are sending a transaction to a given server anyway (for
+        # example, because we have a PDU or a RR in another room to send), then we may
+        # as well send out all of the pending RRs for that server. So it may be that
+        # by the time we get to T+N, we don't actually have any RRs left to send out.
+        # Nevertheless we continue to buffer up RRs for the room in question until we
+        # reach the point that no RRs arrive between timer ticks.
+        #
+        # For even more background, see https://github.com/matrix-org/synapse/issues/4730.
+
+        room_id = receipt.room_id
+
         # Work out which remote servers should be poked and poke them.
-        domains = yield self.state.get_current_hosts_in_room(receipt.room_id)
+        domains = yield self.state.get_current_hosts_in_room(room_id)
         domains = [d for d in domains if d != self.server_name]
         if not domains:
             return
 
-        logger.debug("Sending receipt to: %r", domains)
+        queues_pending_flush = self._queues_awaiting_rr_flush_by_room.get(
+            room_id
+        )
 
-        content = {
-            receipt.room_id: {
-                receipt.receipt_type: {
-                    receipt.user_id: {
-                        "event_ids": receipt.event_ids,
-                        "data": receipt.data,
-                    },
-                },
-            },
-        }
-        key = (receipt.room_id, receipt.receipt_type, receipt.user_id)
+        # if there is no flush yet scheduled, we will send out these receipts with
+        # immediate flushes, and schedule the next flush for this room.
+        if queues_pending_flush is not None:
+            logger.debug("Queuing receipt for: %r", domains)
+        else:
+            logger.debug("Sending receipt to: %r", domains)
+            self._schedule_rr_flush_for_room(room_id, len(domains))
 
         for domain in domains:
-            self.build_and_send_edu(
-                destination=domain,
-                edu_type="m.receipt",
-                content=content,
-                key=key,
-            )
+            queue = self._get_per_destination_queue(domain)
+            queue.queue_read_receipt(receipt)
+
+            # if there is already a RR flush pending for this room, then make sure this
+            # destination is registered for the flush
+            if queues_pending_flush is not None:
+                queues_pending_flush.add(queue)
+            else:
+                queue.flush_read_receipts_for_room(room_id)
+
+    def _schedule_rr_flush_for_room(self, room_id, n_domains):
+        # that is going to cause approximately len(domains) transactions, so now back
+        # off for that multiplied by RR_TXN_INTERVAL_PER_ROOM
+        backoff_ms = self._rr_txn_interval_per_room_ms * n_domains
+
+        logger.debug("Scheduling RR flush in %s in %d ms", room_id, backoff_ms)
+        self.clock.call_later(backoff_ms, self._flush_rrs_for_room, room_id)
+        self._queues_awaiting_rr_flush_by_room[room_id] = set()
+
+    def _flush_rrs_for_room(self, room_id):
+        queues = self._queues_awaiting_rr_flush_by_room.pop(room_id)
+        logger.debug("Flushing RRs in %s to %s", room_id, queues)
+
+        if not queues:
+            # no more RRs arrived for this room; we are done.
+            return
+
+        # schedule the next flush
+        self._schedule_rr_flush_for_room(room_id, len(queues))
+
+        for queue in queues:
+            queue.flush_read_receipts_for_room(room_id)
 
     @logcontext.preserve_fn  # the caller should not yield on this
     @defer.inlineCallbacks
diff --git a/synapse/federation/sender/per_destination_queue.py b/synapse/federation/sender/per_destination_queue.py
index 385039add4..be99211003 100644
--- a/synapse/federation/sender/per_destination_queue.py
+++ b/synapse/federation/sender/per_destination_queue.py
@@ -80,6 +80,10 @@ class PerDestinationQueue(object):
         # destination
         self._pending_presence = {}   # type: dict[str, UserPresenceState]
 
+        # room_id -> receipt_type -> user_id -> receipt_dict
+        self._pending_rrs = {}
+        self._rrs_pending_flush = False
+
         # stream_id of last successfully sent to-device message.
         # NB: may be a long or an int.
         self._last_device_stream_id = 0
@@ -87,6 +91,9 @@ class PerDestinationQueue(object):
         # stream_id of last successfully sent device list update.
         self._last_device_list_stream_id = 0
 
+    def __str__(self):
+        return "PerDestinationQueue[%s]" % self._destination
+
     def pending_pdu_count(self):
         return len(self._pending_pdus)
 
@@ -118,6 +125,30 @@ class PerDestinationQueue(object):
         })
         self.attempt_new_transaction()
 
+    def queue_read_receipt(self, receipt):
+        """Add a RR to the list to be sent. Doesn't start the transmission loop yet
+        (see flush_read_receipts_for_room)
+
+        Args:
+            receipt (synapse.api.receipt_info.ReceiptInfo): receipt to be queued
+        """
+        self._pending_rrs.setdefault(
+            receipt.room_id, {},
+        ).setdefault(
+            receipt.receipt_type, {}
+        )[receipt.user_id] = {
+            "event_ids": receipt.event_ids,
+            "data": receipt.data,
+        }
+
+    def flush_read_receipts_for_room(self, room_id):
+        # if we don't have any read-receipts for this room, it may be that we've already
+        # sent them out, so we don't need to flush.
+        if room_id not in self._pending_rrs:
+            return
+        self._rrs_pending_flush = True
+        self.attempt_new_transaction()
+
     def send_keyed_edu(self, edu, key):
         self._pending_edus_keyed[(edu.edu_type, key)] = edu
         self.attempt_new_transaction()
@@ -183,10 +214,12 @@ class PerDestinationQueue(object):
                 # We can only include at most 50 PDUs per transactions
                 pending_pdus, self._pending_pdus = pending_pdus[:50], pending_pdus[50:]
 
-                pending_edus = self._pending_edus
+                pending_edus = []
+
+                pending_edus.extend(self._get_rr_edus(force_flush=False))
 
                 # We can only include at most 100 EDUs per transactions
-                pending_edus, self._pending_edus = pending_edus[:100], pending_edus[100:]
+                pending_edus.extend(self._pop_pending_edus(100 - len(pending_edus)))
 
                 pending_edus.extend(
                     self._pending_edus_keyed.values()
@@ -224,6 +257,11 @@ class PerDestinationQueue(object):
                     self._last_device_stream_id = device_stream_id
                     return
 
+                # if we've decided to send a transaction anyway, and we have room, we
+                # may as well send any pending RRs
+                if len(pending_edus) < 100:
+                    pending_edus.extend(self._get_rr_edus(force_flush=True))
+
                 # END CRITICAL SECTION
 
                 success = yield self._transaction_manager.send_new_transaction(
@@ -285,6 +323,28 @@ class PerDestinationQueue(object):
             # We want to be *very* sure we clear this after we stop processing
             self.transmission_loop_running = False
 
+    def _get_rr_edus(self, force_flush):
+        if not self._pending_rrs:
+            return
+        if not force_flush and not self._rrs_pending_flush:
+            # not yet time for this lot
+            return
+
+        edu = Edu(
+            origin=self._server_name,
+            destination=self._destination,
+            edu_type="m.receipt",
+            content=self._pending_rrs,
+        )
+        self._pending_rrs = {}
+        self._rrs_pending_flush = False
+        yield edu
+
+    def _pop_pending_edus(self, limit):
+        pending_edus = self._pending_edus
+        pending_edus, self._pending_edus = pending_edus[:limit], pending_edus[limit:]
+        return pending_edus
+
     @defer.inlineCallbacks
     def _get_new_device_messages(self):
         last_device_stream_id = self._last_device_stream_id
diff --git a/synapse/handlers/receipts.py b/synapse/handlers/receipts.py
index dd783ae134..274d2946ad 100644
--- a/synapse/handlers/receipts.py
+++ b/synapse/handlers/receipts.py
@@ -118,7 +118,7 @@ class ReceiptsHandler(BaseHandler):
         if not is_new:
             return
 
-        self.federation.send_read_receipt(receipt)
+        yield self.federation.send_read_receipt(receipt)
 
     @defer.inlineCallbacks
     def get_receipts_for_room(self, room_id, to_key):
diff --git a/synapse/replication/tcp/resource.py b/synapse/replication/tcp/resource.py
index fd59f1595f..47cdf30bd3 100644
--- a/synapse/replication/tcp/resource.py
+++ b/synapse/replication/tcp/resource.py
@@ -16,6 +16,7 @@
 """
 
 import logging
+import random
 
 from six import itervalues
 
@@ -74,6 +75,8 @@ class ReplicationStreamer(object):
         self.notifier = hs.get_notifier()
         self._server_notices_sender = hs.get_server_notices_sender()
 
+        self._replication_torture_level = hs.config.replication_torture_level
+
         # Current connections.
         self.connections = []
 
@@ -157,10 +160,23 @@ class ReplicationStreamer(object):
                     for stream in self.streams:
                         stream.advance_current_token()
 
-                    for stream in self.streams:
+                    all_streams = self.streams
+
+                    if self._replication_torture_level is not None:
+                        # there is no guarantee about ordering between the streams,
+                        # so let's shuffle them around a bit when we are in torture mode.
+                        all_streams = list(all_streams)
+                        random.shuffle(all_streams)
+
+                    for stream in all_streams:
                         if stream.last_token == stream.upto_token:
                             continue
 
+                        if self._replication_torture_level:
+                            yield self.clock.sleep(
+                                self._replication_torture_level / 1000.0
+                            )
+
                         logger.debug(
                             "Getting stream: %s: %s -> %s",
                             stream.NAME, stream.last_token, stream.upto_token
diff --git a/synapse/rest/client/v2_alpha/user_directory.py b/synapse/rest/client/v2_alpha/user_directory.py
index cac0624ba7..36b02de37f 100644
--- a/synapse/rest/client/v2_alpha/user_directory.py
+++ b/synapse/rest/client/v2_alpha/user_directory.py
@@ -59,6 +59,12 @@ class UserDirectorySearchRestServlet(RestServlet):
         requester = yield self.auth.get_user_by_req(request, allow_guest=False)
         user_id = requester.user.to_string()
 
+        if not self.hs.config.user_directory_search_enabled:
+            defer.returnValue((200, {
+                "limited": False,
+                "results": [],
+            }))
+
         body = parse_json_object_from_request(request)
 
         limit = body.get("limit", 10)
diff --git a/synapse/storage/user_directory.py b/synapse/storage/user_directory.py
index 4ee653210f..d360e857d1 100644
--- a/synapse/storage/user_directory.py
+++ b/synapse/storage/user_directory.py
@@ -32,6 +32,11 @@ TEMP_TABLE = "_temp_populate_user_directory"
 
 
 class UserDirectoryStore(BackgroundUpdateStore):
+
+    # How many records do we calculate before sending it to
+    # add_users_who_share_private_rooms?
+    SHARE_PRIVATE_WORKING_SET = 500
+
     def __init__(self, db_conn, hs):
         super(UserDirectoryStore, self).__init__(db_conn, hs)
 
@@ -218,6 +223,14 @@ class UserDirectoryStore(BackgroundUpdateStore):
                             user_set = (user_id, other_user_id)
                             to_insert.add(user_set)
 
+                            # If it gets too big, stop and write to the database
+                            # to prevent storing too much in RAM.
+                            if len(to_insert) >= self.SHARE_PRIVATE_WORKING_SET:
+                                yield self.add_users_who_share_private_room(
+                                    room_id, to_insert
+                                )
+                                to_insert.clear()
+
                     if to_insert:
                         yield self.add_users_who_share_private_room(room_id, to_insert)
                         to_insert.clear()
diff --git a/tests/federation/test_federation_sender.py b/tests/federation/test_federation_sender.py
new file mode 100644
index 0000000000..28e7e27416
--- /dev/null
+++ b/tests/federation/test_federation_sender.py
@@ -0,0 +1,128 @@
+# -*- coding: utf-8 -*-
+# Copyright 2019 New Vector Ltd
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from mock import Mock
+
+from twisted.internet import defer
+
+from synapse.types import ReadReceipt
+
+from tests.unittest import HomeserverTestCase
+
+
+class FederationSenderTestCases(HomeserverTestCase):
+    def make_homeserver(self, reactor, clock):
+        return super(FederationSenderTestCases, self).setup_test_homeserver(
+            state_handler=Mock(spec=["get_current_hosts_in_room"]),
+            federation_transport_client=Mock(spec=["send_transaction"]),
+        )
+
+    def test_send_receipts(self):
+        mock_state_handler = self.hs.get_state_handler()
+        mock_state_handler.get_current_hosts_in_room.return_value = ["test", "host2"]
+
+        mock_send_transaction = self.hs.get_federation_transport_client().send_transaction
+        mock_send_transaction.return_value = defer.succeed({})
+
+        sender = self.hs.get_federation_sender()
+        receipt = ReadReceipt("room_id", "m.read", "user_id", ["event_id"], {"ts": 1234})
+        self.successResultOf(sender.send_read_receipt(receipt))
+
+        self.pump()
+
+        # expect a call to send_transaction
+        mock_send_transaction.assert_called_once()
+        json_cb = mock_send_transaction.call_args[0][1]
+        data = json_cb()
+        self.assertEqual(data['edus'], [
+            {
+                'edu_type': 'm.receipt',
+                'content': {
+                    'room_id': {
+                        'm.read': {
+                            'user_id': {
+                                'event_ids': ['event_id'],
+                                'data': {'ts': 1234},
+                            },
+                        },
+                    },
+                },
+            },
+        ])
+
+    def test_send_receipts_with_backoff(self):
+        """Send two receipts in quick succession; the second should be flushed, but
+        only after 20ms"""
+        mock_state_handler = self.hs.get_state_handler()
+        mock_state_handler.get_current_hosts_in_room.return_value = ["test", "host2"]
+
+        mock_send_transaction = self.hs.get_federation_transport_client().send_transaction
+        mock_send_transaction.return_value = defer.succeed({})
+
+        sender = self.hs.get_federation_sender()
+        receipt = ReadReceipt("room_id", "m.read", "user_id", ["event_id"], {"ts": 1234})
+        self.successResultOf(sender.send_read_receipt(receipt))
+
+        self.pump()
+
+        # expect a call to send_transaction
+        mock_send_transaction.assert_called_once()
+        json_cb = mock_send_transaction.call_args[0][1]
+        data = json_cb()
+        self.assertEqual(data['edus'], [
+            {
+                'edu_type': 'm.receipt',
+                'content': {
+                    'room_id': {
+                        'm.read': {
+                            'user_id': {
+                                'event_ids': ['event_id'],
+                                'data': {'ts': 1234},
+                            },
+                        },
+                    },
+                },
+            },
+        ])
+        mock_send_transaction.reset_mock()
+
+        # send the second RR
+        receipt = ReadReceipt("room_id", "m.read", "user_id", ["other_id"], {"ts": 1234})
+        self.successResultOf(sender.send_read_receipt(receipt))
+        self.pump()
+        mock_send_transaction.assert_not_called()
+
+        self.reactor.advance(19)
+        mock_send_transaction.assert_not_called()
+
+        self.reactor.advance(10)
+        mock_send_transaction.assert_called_once()
+        json_cb = mock_send_transaction.call_args[0][1]
+        data = json_cb()
+        self.assertEqual(data['edus'], [
+            {
+                'edu_type': 'm.receipt',
+                'content': {
+                    'room_id': {
+                        'm.read': {
+                            'user_id': {
+                                'event_ids': ['other_id'],
+                                'data': {'ts': 1234},
+                            },
+                        },
+                    },
+                },
+            },
+        ])
diff --git a/tests/handlers/test_user_directory.py b/tests/handlers/test_user_directory.py
index aefe11ac28..f1d0aa42b6 100644
--- a/tests/handlers/test_user_directory.py
+++ b/tests/handlers/test_user_directory.py
@@ -16,6 +16,7 @@ from mock import Mock
 
 from synapse.api.constants import UserTypes
 from synapse.rest.client.v1 import admin, login, room
+from synapse.rest.client.v2_alpha import user_directory
 from synapse.storage.roommember import ProfileInfo
 
 from tests import unittest
@@ -317,3 +318,54 @@ class UserDirectoryTestCase(unittest.HomeserverTestCase):
         u4 = self.register_user("user4", "pass")
         s = self.get_success(self.handler.search_users(u1, u4, 10))
         self.assertEqual(len(s["results"]), 1)
+
+
+class TestUserDirSearchDisabled(unittest.HomeserverTestCase):
+    user_id = "@test:test"
+
+    servlets = [
+        user_directory.register_servlets,
+        room.register_servlets,
+        login.register_servlets,
+        admin.register_servlets,
+    ]
+
+    def make_homeserver(self, reactor, clock):
+        config = self.default_config()
+        config.update_user_directory = True
+        hs = self.setup_test_homeserver(config=config)
+
+        self.config = hs.config
+
+        return hs
+
+    def test_disabling_room_list(self):
+        self.config.user_directory_search_enabled = True
+
+        # First we create a room with another user so that user dir is non-empty
+        # for our user
+        self.helper.create_room_as(self.user_id)
+        u2 = self.register_user("user2", "pass")
+        room = self.helper.create_room_as(self.user_id)
+        self.helper.join(room, user=u2)
+
+        # Assert user directory is not empty
+        request, channel = self.make_request(
+            "POST",
+            b"user_directory/search",
+            b'{"search_term":"user2"}',
+        )
+        self.render(request)
+        self.assertEquals(200, channel.code, channel.result)
+        self.assertTrue(len(channel.json_body["results"]) > 0)
+
+        # Disable user directory and check search returns nothing
+        self.config.user_directory_search_enabled = False
+        request, channel = self.make_request(
+            "POST",
+            b"user_directory/search",
+            b'{"search_term":"user2"}',
+        )
+        self.render(request)
+        self.assertEquals(200, channel.code, channel.result)
+        self.assertTrue(len(channel.json_body["results"]) == 0)
diff --git a/tests/server.py b/tests/server.py
index 37069afdda..ea26dea623 100644
--- a/tests/server.py
+++ b/tests/server.py
@@ -119,14 +119,7 @@ class FakeSite:
 
     server_version_string = b"1"
     site_tag = "test"
-
-    @property
-    def access_logger(self):
-        class FakeLogger:
-            def info(self, *args, **kwargs):
-                pass
-
-        return FakeLogger()
+    access_logger = logging.getLogger("synapse.access.http.fake")
 
 
 def make_request(