server.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # This file provides some classes for setting up (partially-populated)
  15. # homeservers; either as a full homeserver as a real application, or a small
  16. # partial one for unit test mocking.
  17. import abc
  18. import functools
  19. import logging
  20. from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, TypeVar, cast
  21. from twisted.internet.interfaces import IOpenSSLContextFactory
  22. from twisted.internet.tcp import Port
  23. from twisted.web.iweb import IPolicyForHTTPS
  24. from twisted.web.resource import Resource
  25. from synapse.api.auth import Auth
  26. from synapse.api.filtering import Filtering
  27. from synapse.api.ratelimiting import Ratelimiter, RequestRatelimiter
  28. from synapse.appservice.api import ApplicationServiceApi
  29. from synapse.appservice.scheduler import ApplicationServiceScheduler
  30. from synapse.config.homeserver import HomeServerConfig
  31. from synapse.crypto import context_factory
  32. from synapse.crypto.context_factory import RegularPolicyForHTTPS
  33. from synapse.crypto.keyring import Keyring
  34. from synapse.events.builder import EventBuilderFactory
  35. from synapse.events.presence_router import PresenceRouter
  36. from synapse.events.spamcheck import SpamChecker
  37. from synapse.events.third_party_rules import ThirdPartyEventRules
  38. from synapse.events.utils import EventClientSerializer
  39. from synapse.federation.federation_client import FederationClient
  40. from synapse.federation.federation_server import (
  41. FederationHandlerRegistry,
  42. FederationServer,
  43. )
  44. from synapse.federation.send_queue import FederationRemoteSendQueue
  45. from synapse.federation.sender import AbstractFederationSender, FederationSender
  46. from synapse.federation.transport.client import TransportLayerClient
  47. from synapse.handlers.account import AccountHandler
  48. from synapse.handlers.account_data import AccountDataHandler
  49. from synapse.handlers.account_validity import AccountValidityHandler
  50. from synapse.handlers.admin import AdminHandler
  51. from synapse.handlers.appservice import ApplicationServicesHandler
  52. from synapse.handlers.auth import AuthHandler, MacaroonGenerator, PasswordAuthProvider
  53. from synapse.handlers.cas import CasHandler
  54. from synapse.handlers.deactivate_account import DeactivateAccountHandler
  55. from synapse.handlers.device import DeviceHandler, DeviceWorkerHandler
  56. from synapse.handlers.devicemessage import DeviceMessageHandler
  57. from synapse.handlers.directory import DirectoryHandler
  58. from synapse.handlers.e2e_keys import E2eKeysHandler
  59. from synapse.handlers.e2e_room_keys import E2eRoomKeysHandler
  60. from synapse.handlers.event_auth import EventAuthHandler
  61. from synapse.handlers.events import EventHandler, EventStreamHandler
  62. from synapse.handlers.federation import FederationHandler
  63. from synapse.handlers.federation_event import FederationEventHandler
  64. from synapse.handlers.identity import IdentityHandler
  65. from synapse.handlers.initial_sync import InitialSyncHandler
  66. from synapse.handlers.message import EventCreationHandler, MessageHandler
  67. from synapse.handlers.pagination import PaginationHandler
  68. from synapse.handlers.password_policy import PasswordPolicyHandler
  69. from synapse.handlers.presence import (
  70. BasePresenceHandler,
  71. PresenceHandler,
  72. WorkerPresenceHandler,
  73. )
  74. from synapse.handlers.profile import ProfileHandler
  75. from synapse.handlers.push_rules import PushRulesHandler
  76. from synapse.handlers.read_marker import ReadMarkerHandler
  77. from synapse.handlers.receipts import ReceiptsHandler
  78. from synapse.handlers.register import RegistrationHandler
  79. from synapse.handlers.relations import RelationsHandler
  80. from synapse.handlers.room import (
  81. RoomContextHandler,
  82. RoomCreationHandler,
  83. RoomShutdownHandler,
  84. TimestampLookupHandler,
  85. )
  86. from synapse.handlers.room_batch import RoomBatchHandler
  87. from synapse.handlers.room_list import RoomListHandler
  88. from synapse.handlers.room_member import RoomMemberHandler, RoomMemberMasterHandler
  89. from synapse.handlers.room_member_worker import RoomMemberWorkerHandler
  90. from synapse.handlers.room_summary import RoomSummaryHandler
  91. from synapse.handlers.search import SearchHandler
  92. from synapse.handlers.send_email import SendEmailHandler
  93. from synapse.handlers.set_password import SetPasswordHandler
  94. from synapse.handlers.sso import SsoHandler
  95. from synapse.handlers.stats import StatsHandler
  96. from synapse.handlers.sync import SyncHandler
  97. from synapse.handlers.typing import FollowerTypingHandler, TypingWriterHandler
  98. from synapse.handlers.user_directory import UserDirectoryHandler
  99. from synapse.http.client import InsecureInterceptableContextFactory, SimpleHttpClient
  100. from synapse.http.matrixfederationclient import MatrixFederationHttpClient
  101. from synapse.module_api import ModuleApi
  102. from synapse.notifier import Notifier
  103. from synapse.push.bulk_push_rule_evaluator import BulkPushRuleEvaluator
  104. from synapse.push.pusherpool import PusherPool
  105. from synapse.replication.tcp.client import ReplicationDataHandler
  106. from synapse.replication.tcp.external_cache import ExternalCache
  107. from synapse.replication.tcp.handler import ReplicationCommandHandler
  108. from synapse.replication.tcp.resource import ReplicationStreamer
  109. from synapse.replication.tcp.streams import STREAMS_MAP, Stream
  110. from synapse.rest.media.v1.media_repository import (
  111. MediaRepository,
  112. MediaRepositoryResource,
  113. )
  114. from synapse.server_notices.server_notices_manager import ServerNoticesManager
  115. from synapse.server_notices.server_notices_sender import ServerNoticesSender
  116. from synapse.server_notices.worker_server_notices_sender import (
  117. WorkerServerNoticesSender,
  118. )
  119. from synapse.state import StateHandler, StateResolutionHandler
  120. from synapse.storage import Databases
  121. from synapse.storage.controllers import StorageControllers
  122. from synapse.streams.events import EventSources
  123. from synapse.types import DomainSpecificString, ISynapseReactor
  124. from synapse.util import Clock
  125. from synapse.util.distributor import Distributor
  126. from synapse.util.ratelimitutils import FederationRateLimiter
  127. from synapse.util.stringutils import random_string
  128. logger = logging.getLogger(__name__)
  129. if TYPE_CHECKING:
  130. from txredisapi import ConnectionHandler
  131. from synapse.handlers.oidc import OidcHandler
  132. from synapse.handlers.saml import SamlHandler
  133. T = TypeVar("T", bound=Callable[..., Any])
  134. def cache_in_self(builder: T) -> T:
  135. """Wraps a function called e.g. `get_foo`, checking if `self.foo` exists and
  136. returning if so. If not, calls the given function and sets `self.foo` to it.
  137. Also ensures that dependency cycles throw an exception correctly, rather
  138. than overflowing the stack.
  139. """
  140. if not builder.__name__.startswith("get_"):
  141. raise Exception(
  142. "@cache_in_self can only be used on functions starting with `get_`"
  143. )
  144. # get_attr -> _attr
  145. depname = builder.__name__[len("get") :]
  146. building = [False]
  147. @functools.wraps(builder)
  148. def _get(self):
  149. try:
  150. return getattr(self, depname)
  151. except AttributeError:
  152. pass
  153. # Prevent cyclic dependencies from deadlocking
  154. if building[0]:
  155. raise ValueError("Cyclic dependency while building %s" % (depname,))
  156. building[0] = True
  157. try:
  158. dep = builder(self)
  159. setattr(self, depname, dep)
  160. finally:
  161. building[0] = False
  162. return dep
  163. # We cast here as we need to tell mypy that `_get` has the same signature as
  164. # `builder`.
  165. return cast(T, _get)
  166. class HomeServer(metaclass=abc.ABCMeta):
  167. """A basic homeserver object without lazy component builders.
  168. This will need all of the components it requires to either be passed as
  169. constructor arguments, or the relevant methods overriding to create them.
  170. Typically this would only be used for unit tests.
  171. Dependencies should be added by creating a `def get_<depname>(self)`
  172. function, wrapping it in `@cache_in_self`.
  173. Attributes:
  174. config (synapse.config.homeserver.HomeserverConfig):
  175. _listening_services (list[Port]): TCP ports that
  176. we are listening on to provide HTTP services.
  177. """
  178. REQUIRED_ON_BACKGROUND_TASK_STARTUP = [
  179. "account_validity",
  180. "auth",
  181. "deactivate_account",
  182. "message",
  183. "pagination",
  184. "profile",
  185. "stats",
  186. ]
  187. # This is overridden in derived application classes
  188. # (such as synapse.app.homeserver.SynapseHomeServer) and gives the class to be
  189. # instantiated during setup() for future return by get_datastores()
  190. DATASTORE_CLASS = abc.abstractproperty()
  191. tls_server_context_factory: Optional[IOpenSSLContextFactory]
  192. def __init__(
  193. self,
  194. hostname: str,
  195. config: HomeServerConfig,
  196. reactor: Optional[ISynapseReactor] = None,
  197. version_string: str = "Synapse",
  198. ):
  199. """
  200. Args:
  201. hostname : The hostname for the server.
  202. config: The full config for the homeserver.
  203. """
  204. if not reactor:
  205. from twisted.internet import reactor as _reactor
  206. reactor = cast(ISynapseReactor, _reactor)
  207. self._reactor = reactor
  208. self.hostname = hostname
  209. # the key we use to sign events and requests
  210. self.signing_key = config.key.signing_key[0]
  211. self.config = config
  212. self._listening_services: List[Port] = []
  213. self.start_time: Optional[int] = None
  214. self._instance_id = random_string(5)
  215. self._instance_name = config.worker.instance_name
  216. self.version_string = version_string
  217. self.datastores: Optional[Databases] = None
  218. self._module_web_resources: Dict[str, Resource] = {}
  219. self._module_web_resources_consumed = False
  220. def register_module_web_resource(self, path: str, resource: Resource) -> None:
  221. """Allows a module to register a web resource to be served at the given path.
  222. If multiple modules register a resource for the same path, the module that
  223. appears the highest in the configuration file takes priority.
  224. Args:
  225. path: The path to register the resource for.
  226. resource: The resource to attach to this path.
  227. Raises:
  228. SynapseError(500): A module tried to register a web resource after the HTTP
  229. listeners have been started.
  230. """
  231. if self._module_web_resources_consumed:
  232. raise RuntimeError(
  233. "Tried to register a web resource from a module after startup",
  234. )
  235. # Don't register a resource that's already been registered.
  236. if path not in self._module_web_resources.keys():
  237. self._module_web_resources[path] = resource
  238. else:
  239. logger.warning(
  240. "Module tried to register a web resource for path %s but another module"
  241. " has already registered a resource for this path.",
  242. path,
  243. )
  244. def get_instance_id(self) -> str:
  245. """A unique ID for this synapse process instance.
  246. This is used to distinguish running instances in worker-based
  247. deployments.
  248. """
  249. return self._instance_id
  250. def get_instance_name(self) -> str:
  251. """A unique name for this synapse process.
  252. Used to identify the process over replication and in config. Does not
  253. change over restarts.
  254. """
  255. return self._instance_name
  256. def setup(self) -> None:
  257. logger.info("Setting up.")
  258. self.start_time = int(self.get_clock().time())
  259. self.datastores = Databases(self.DATASTORE_CLASS, self)
  260. logger.info("Finished setting up.")
  261. # Register background tasks required by this server. This must be done
  262. # somewhat manually due to the background tasks not being registered
  263. # unless handlers are instantiated.
  264. if self.config.worker.run_background_tasks:
  265. self.setup_background_tasks()
  266. def start_listening(self) -> None:
  267. """Start the HTTP, manhole, metrics, etc listeners
  268. Does nothing in this base class; overridden in derived classes to start the
  269. appropriate listeners.
  270. """
  271. def setup_background_tasks(self) -> None:
  272. """
  273. Some handlers have side effects on instantiation (like registering
  274. background updates). This function causes them to be fetched, and
  275. therefore instantiated, to run those side effects.
  276. """
  277. for i in self.REQUIRED_ON_BACKGROUND_TASK_STARTUP:
  278. getattr(self, "get_" + i + "_handler")()
  279. def get_reactor(self) -> ISynapseReactor:
  280. """
  281. Fetch the Twisted reactor in use by this HomeServer.
  282. """
  283. return self._reactor
  284. def is_mine(self, domain_specific_string: DomainSpecificString) -> bool:
  285. return domain_specific_string.domain == self.hostname
  286. def is_mine_id(self, string: str) -> bool:
  287. return string.split(":", 1)[1] == self.hostname
  288. @cache_in_self
  289. def get_clock(self) -> Clock:
  290. return Clock(self._reactor)
  291. def get_datastores(self) -> Databases:
  292. if not self.datastores:
  293. raise Exception("HomeServer.setup must be called before getting datastores")
  294. return self.datastores
  295. @cache_in_self
  296. def get_distributor(self) -> Distributor:
  297. return Distributor()
  298. @cache_in_self
  299. def get_registration_ratelimiter(self) -> Ratelimiter:
  300. return Ratelimiter(
  301. store=self.get_datastores().main,
  302. clock=self.get_clock(),
  303. rate_hz=self.config.ratelimiting.rc_registration.per_second,
  304. burst_count=self.config.ratelimiting.rc_registration.burst_count,
  305. )
  306. @cache_in_self
  307. def get_federation_client(self) -> FederationClient:
  308. return FederationClient(self)
  309. @cache_in_self
  310. def get_federation_server(self) -> FederationServer:
  311. return FederationServer(self)
  312. @cache_in_self
  313. def get_notifier(self) -> Notifier:
  314. return Notifier(self)
  315. @cache_in_self
  316. def get_auth(self) -> Auth:
  317. return Auth(self)
  318. @cache_in_self
  319. def get_http_client_context_factory(self) -> IPolicyForHTTPS:
  320. if self.config.tls.use_insecure_ssl_client_just_for_testing_do_not_use:
  321. return InsecureInterceptableContextFactory()
  322. return RegularPolicyForHTTPS()
  323. @cache_in_self
  324. def get_simple_http_client(self) -> SimpleHttpClient:
  325. """
  326. An HTTP client with no special configuration.
  327. """
  328. return SimpleHttpClient(self)
  329. @cache_in_self
  330. def get_proxied_http_client(self) -> SimpleHttpClient:
  331. """
  332. An HTTP client that uses configured HTTP(S) proxies.
  333. """
  334. return SimpleHttpClient(self, use_proxy=True)
  335. @cache_in_self
  336. def get_proxied_blacklisted_http_client(self) -> SimpleHttpClient:
  337. """
  338. An HTTP client that uses configured HTTP(S) proxies and blacklists IPs
  339. based on the IP range blacklist/whitelist.
  340. """
  341. return SimpleHttpClient(
  342. self,
  343. ip_whitelist=self.config.server.ip_range_whitelist,
  344. ip_blacklist=self.config.server.ip_range_blacklist,
  345. use_proxy=True,
  346. )
  347. @cache_in_self
  348. def get_federation_http_client(self) -> MatrixFederationHttpClient:
  349. """
  350. An HTTP client for federation.
  351. """
  352. tls_client_options_factory = context_factory.FederationPolicyForHTTPS(
  353. self.config
  354. )
  355. return MatrixFederationHttpClient(self, tls_client_options_factory)
  356. @cache_in_self
  357. def get_room_creation_handler(self) -> RoomCreationHandler:
  358. return RoomCreationHandler(self)
  359. @cache_in_self
  360. def get_room_batch_handler(self) -> RoomBatchHandler:
  361. return RoomBatchHandler(self)
  362. @cache_in_self
  363. def get_room_shutdown_handler(self) -> RoomShutdownHandler:
  364. return RoomShutdownHandler(self)
  365. @cache_in_self
  366. def get_state_handler(self) -> StateHandler:
  367. return StateHandler(self)
  368. @cache_in_self
  369. def get_state_resolution_handler(self) -> StateResolutionHandler:
  370. return StateResolutionHandler(self)
  371. @cache_in_self
  372. def get_presence_handler(self) -> BasePresenceHandler:
  373. if self.get_instance_name() in self.config.worker.writers.presence:
  374. return PresenceHandler(self)
  375. else:
  376. return WorkerPresenceHandler(self)
  377. @cache_in_self
  378. def get_typing_writer_handler(self) -> TypingWriterHandler:
  379. if self.get_instance_name() in self.config.worker.writers.typing:
  380. return TypingWriterHandler(self)
  381. else:
  382. raise Exception("Workers cannot write typing")
  383. @cache_in_self
  384. def get_presence_router(self) -> PresenceRouter:
  385. return PresenceRouter(self)
  386. @cache_in_self
  387. def get_typing_handler(self) -> FollowerTypingHandler:
  388. if self.get_instance_name() in self.config.worker.writers.typing:
  389. # Use get_typing_writer_handler to ensure that we use the same
  390. # cached version.
  391. return self.get_typing_writer_handler()
  392. else:
  393. return FollowerTypingHandler(self)
  394. @cache_in_self
  395. def get_sso_handler(self) -> SsoHandler:
  396. return SsoHandler(self)
  397. @cache_in_self
  398. def get_sync_handler(self) -> SyncHandler:
  399. return SyncHandler(self)
  400. @cache_in_self
  401. def get_room_list_handler(self) -> RoomListHandler:
  402. return RoomListHandler(self)
  403. @cache_in_self
  404. def get_auth_handler(self) -> AuthHandler:
  405. return AuthHandler(self)
  406. @cache_in_self
  407. def get_macaroon_generator(self) -> MacaroonGenerator:
  408. return MacaroonGenerator(self)
  409. @cache_in_self
  410. def get_device_handler(self):
  411. if self.config.worker.worker_app:
  412. return DeviceWorkerHandler(self)
  413. else:
  414. return DeviceHandler(self)
  415. @cache_in_self
  416. def get_device_message_handler(self) -> DeviceMessageHandler:
  417. return DeviceMessageHandler(self)
  418. @cache_in_self
  419. def get_directory_handler(self) -> DirectoryHandler:
  420. return DirectoryHandler(self)
  421. @cache_in_self
  422. def get_e2e_keys_handler(self) -> E2eKeysHandler:
  423. return E2eKeysHandler(self)
  424. @cache_in_self
  425. def get_e2e_room_keys_handler(self) -> E2eRoomKeysHandler:
  426. return E2eRoomKeysHandler(self)
  427. @cache_in_self
  428. def get_admin_handler(self) -> AdminHandler:
  429. return AdminHandler(self)
  430. @cache_in_self
  431. def get_application_service_api(self) -> ApplicationServiceApi:
  432. return ApplicationServiceApi(self)
  433. @cache_in_self
  434. def get_application_service_scheduler(self) -> ApplicationServiceScheduler:
  435. return ApplicationServiceScheduler(self)
  436. @cache_in_self
  437. def get_application_service_handler(self) -> ApplicationServicesHandler:
  438. return ApplicationServicesHandler(self)
  439. @cache_in_self
  440. def get_event_handler(self) -> EventHandler:
  441. return EventHandler(self)
  442. @cache_in_self
  443. def get_event_stream_handler(self) -> EventStreamHandler:
  444. return EventStreamHandler(self)
  445. @cache_in_self
  446. def get_federation_handler(self) -> FederationHandler:
  447. return FederationHandler(self)
  448. @cache_in_self
  449. def get_federation_event_handler(self) -> FederationEventHandler:
  450. return FederationEventHandler(self)
  451. @cache_in_self
  452. def get_identity_handler(self) -> IdentityHandler:
  453. return IdentityHandler(self)
  454. @cache_in_self
  455. def get_initial_sync_handler(self) -> InitialSyncHandler:
  456. return InitialSyncHandler(self)
  457. @cache_in_self
  458. def get_profile_handler(self) -> ProfileHandler:
  459. return ProfileHandler(self)
  460. @cache_in_self
  461. def get_event_creation_handler(self) -> EventCreationHandler:
  462. return EventCreationHandler(self)
  463. @cache_in_self
  464. def get_deactivate_account_handler(self) -> DeactivateAccountHandler:
  465. return DeactivateAccountHandler(self)
  466. @cache_in_self
  467. def get_search_handler(self) -> SearchHandler:
  468. return SearchHandler(self)
  469. @cache_in_self
  470. def get_send_email_handler(self) -> SendEmailHandler:
  471. return SendEmailHandler(self)
  472. @cache_in_self
  473. def get_set_password_handler(self) -> SetPasswordHandler:
  474. return SetPasswordHandler(self)
  475. @cache_in_self
  476. def get_event_sources(self) -> EventSources:
  477. return EventSources(self)
  478. @cache_in_self
  479. def get_keyring(self) -> Keyring:
  480. return Keyring(self)
  481. @cache_in_self
  482. def get_event_builder_factory(self) -> EventBuilderFactory:
  483. return EventBuilderFactory(self)
  484. @cache_in_self
  485. def get_filtering(self) -> Filtering:
  486. return Filtering(self)
  487. @cache_in_self
  488. def get_pusherpool(self) -> PusherPool:
  489. return PusherPool(self)
  490. @cache_in_self
  491. def get_media_repository_resource(self) -> MediaRepositoryResource:
  492. # build the media repo resource. This indirects through the HomeServer
  493. # to ensure that we only have a single instance of
  494. return MediaRepositoryResource(self)
  495. @cache_in_self
  496. def get_media_repository(self) -> MediaRepository:
  497. return MediaRepository(self)
  498. @cache_in_self
  499. def get_federation_transport_client(self) -> TransportLayerClient:
  500. return TransportLayerClient(self)
  501. @cache_in_self
  502. def get_federation_sender(self) -> AbstractFederationSender:
  503. if self.should_send_federation():
  504. return FederationSender(self)
  505. elif not self.config.worker.worker_app:
  506. return FederationRemoteSendQueue(self)
  507. else:
  508. raise Exception("Workers cannot send federation traffic")
  509. @cache_in_self
  510. def get_receipts_handler(self) -> ReceiptsHandler:
  511. return ReceiptsHandler(self)
  512. @cache_in_self
  513. def get_read_marker_handler(self) -> ReadMarkerHandler:
  514. return ReadMarkerHandler(self)
  515. @cache_in_self
  516. def get_replication_command_handler(self) -> ReplicationCommandHandler:
  517. return ReplicationCommandHandler(self)
  518. @cache_in_self
  519. def get_bulk_push_rule_evaluator(self) -> BulkPushRuleEvaluator:
  520. return BulkPushRuleEvaluator(self)
  521. @cache_in_self
  522. def get_user_directory_handler(self) -> UserDirectoryHandler:
  523. return UserDirectoryHandler(self)
  524. @cache_in_self
  525. def get_stats_handler(self) -> StatsHandler:
  526. return StatsHandler(self)
  527. @cache_in_self
  528. def get_spam_checker(self) -> SpamChecker:
  529. return SpamChecker(self)
  530. @cache_in_self
  531. def get_third_party_event_rules(self) -> ThirdPartyEventRules:
  532. return ThirdPartyEventRules(self)
  533. @cache_in_self
  534. def get_password_auth_provider(self) -> PasswordAuthProvider:
  535. return PasswordAuthProvider()
  536. @cache_in_self
  537. def get_room_member_handler(self) -> RoomMemberHandler:
  538. if self.config.worker.worker_app:
  539. return RoomMemberWorkerHandler(self)
  540. return RoomMemberMasterHandler(self)
  541. @cache_in_self
  542. def get_federation_registry(self) -> FederationHandlerRegistry:
  543. return FederationHandlerRegistry(self)
  544. @cache_in_self
  545. def get_server_notices_manager(self) -> ServerNoticesManager:
  546. if self.config.worker.worker_app:
  547. raise Exception("Workers cannot send server notices")
  548. return ServerNoticesManager(self)
  549. @cache_in_self
  550. def get_server_notices_sender(self) -> WorkerServerNoticesSender:
  551. if self.config.worker.worker_app:
  552. return WorkerServerNoticesSender(self)
  553. return ServerNoticesSender(self)
  554. @cache_in_self
  555. def get_message_handler(self) -> MessageHandler:
  556. return MessageHandler(self)
  557. @cache_in_self
  558. def get_pagination_handler(self) -> PaginationHandler:
  559. return PaginationHandler(self)
  560. @cache_in_self
  561. def get_relations_handler(self) -> RelationsHandler:
  562. return RelationsHandler(self)
  563. @cache_in_self
  564. def get_room_context_handler(self) -> RoomContextHandler:
  565. return RoomContextHandler(self)
  566. @cache_in_self
  567. def get_timestamp_lookup_handler(self) -> TimestampLookupHandler:
  568. return TimestampLookupHandler(self)
  569. @cache_in_self
  570. def get_registration_handler(self) -> RegistrationHandler:
  571. return RegistrationHandler(self)
  572. @cache_in_self
  573. def get_account_validity_handler(self) -> AccountValidityHandler:
  574. return AccountValidityHandler(self)
  575. @cache_in_self
  576. def get_cas_handler(self) -> CasHandler:
  577. return CasHandler(self)
  578. @cache_in_self
  579. def get_saml_handler(self) -> "SamlHandler":
  580. from synapse.handlers.saml import SamlHandler
  581. return SamlHandler(self)
  582. @cache_in_self
  583. def get_oidc_handler(self) -> "OidcHandler":
  584. from synapse.handlers.oidc import OidcHandler
  585. return OidcHandler(self)
  586. @cache_in_self
  587. def get_event_client_serializer(self) -> EventClientSerializer:
  588. return EventClientSerializer()
  589. @cache_in_self
  590. def get_password_policy_handler(self) -> PasswordPolicyHandler:
  591. return PasswordPolicyHandler(self)
  592. @cache_in_self
  593. def get_storage_controllers(self) -> StorageControllers:
  594. return StorageControllers(self, self.get_datastores())
  595. @cache_in_self
  596. def get_replication_streamer(self) -> ReplicationStreamer:
  597. return ReplicationStreamer(self)
  598. @cache_in_self
  599. def get_replication_data_handler(self) -> ReplicationDataHandler:
  600. return ReplicationDataHandler(self)
  601. @cache_in_self
  602. def get_replication_streams(self) -> Dict[str, Stream]:
  603. return {stream.NAME: stream(self) for stream in STREAMS_MAP.values()}
  604. @cache_in_self
  605. def get_federation_ratelimiter(self) -> FederationRateLimiter:
  606. return FederationRateLimiter(
  607. self.get_clock(), config=self.config.ratelimiting.rc_federation
  608. )
  609. @cache_in_self
  610. def get_module_api(self) -> ModuleApi:
  611. return ModuleApi(self, self.get_auth_handler())
  612. @cache_in_self
  613. def get_account_data_handler(self) -> AccountDataHandler:
  614. return AccountDataHandler(self)
  615. @cache_in_self
  616. def get_room_summary_handler(self) -> RoomSummaryHandler:
  617. return RoomSummaryHandler(self)
  618. @cache_in_self
  619. def get_event_auth_handler(self) -> EventAuthHandler:
  620. return EventAuthHandler(self)
  621. @cache_in_self
  622. def get_external_cache(self) -> ExternalCache:
  623. return ExternalCache(self)
  624. @cache_in_self
  625. def get_account_handler(self) -> AccountHandler:
  626. return AccountHandler(self)
  627. @cache_in_self
  628. def get_push_rules_handler(self) -> PushRulesHandler:
  629. return PushRulesHandler(self)
  630. @cache_in_self
  631. def get_outbound_redis_connection(self) -> "ConnectionHandler":
  632. """
  633. The Redis connection used for replication.
  634. Raises:
  635. AssertionError: if Redis is not enabled in the homeserver config.
  636. """
  637. assert self.config.redis.redis_enabled
  638. # We only want to import redis module if we're using it, as we have
  639. # `txredisapi` as an optional dependency.
  640. from synapse.replication.tcp.redis import lazyConnection
  641. logger.info(
  642. "Connecting to redis (host=%r port=%r) for external cache",
  643. self.config.redis.redis_host,
  644. self.config.redis.redis_port,
  645. )
  646. return lazyConnection(
  647. hs=self,
  648. host=self.config.redis.redis_host,
  649. port=self.config.redis.redis_port,
  650. password=self.config.redis.redis_password,
  651. reconnect=True,
  652. )
  653. def should_send_federation(self) -> bool:
  654. "Should this server be sending federation traffic directly?"
  655. return self.config.worker.send_federation
  656. @cache_in_self
  657. def get_request_ratelimiter(self) -> RequestRatelimiter:
  658. return RequestRatelimiter(
  659. self.get_datastores().main,
  660. self.get_clock(),
  661. self.config.ratelimiting.rc_message,
  662. self.config.ratelimiting.rc_admin_redaction,
  663. )