You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

812 rivejä
27 KiB

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