server.py 28 KB

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