Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

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