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.
 
 
 
 
 
 

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