Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

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