server.py 29 KB

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