server.py 29 KB

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