server.py 26 KB

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