matrix-synapse 1.142.0rc3__cp314-abi3-musllinux_1_2_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of matrix-synapse might be problematic. Click here for more details.

Files changed (1057) hide show
  1. matrix_synapse-1.142.0rc3.dist-info/AUTHORS.rst +51 -0
  2. matrix_synapse-1.142.0rc3.dist-info/LICENSE-AGPL-3.0 +661 -0
  3. matrix_synapse-1.142.0rc3.dist-info/LICENSE-COMMERCIAL +6 -0
  4. matrix_synapse-1.142.0rc3.dist-info/METADATA +375 -0
  5. matrix_synapse-1.142.0rc3.dist-info/RECORD +1057 -0
  6. matrix_synapse-1.142.0rc3.dist-info/WHEEL +4 -0
  7. matrix_synapse-1.142.0rc3.dist-info/entry_points.txt +14 -0
  8. matrix_synapse.libs/libgcc_s-2d945d6c.so.1 +0 -0
  9. synapse/__init__.py +97 -0
  10. synapse/_scripts/__init__.py +0 -0
  11. synapse/_scripts/export_signing_key.py +109 -0
  12. synapse/_scripts/generate_config.py +83 -0
  13. synapse/_scripts/generate_log_config.py +56 -0
  14. synapse/_scripts/generate_signing_key.py +55 -0
  15. synapse/_scripts/generate_workers_map.py +318 -0
  16. synapse/_scripts/hash_password.py +95 -0
  17. synapse/_scripts/move_remote_media_to_new_store.py +128 -0
  18. synapse/_scripts/register_new_matrix_user.py +374 -0
  19. synapse/_scripts/review_recent_signups.py +212 -0
  20. synapse/_scripts/synapse_port_db.py +1603 -0
  21. synapse/_scripts/synctl.py +365 -0
  22. synapse/_scripts/update_synapse_database.py +130 -0
  23. synapse/api/__init__.py +20 -0
  24. synapse/api/auth/__init__.py +207 -0
  25. synapse/api/auth/base.py +406 -0
  26. synapse/api/auth/internal.py +299 -0
  27. synapse/api/auth/mas.py +457 -0
  28. synapse/api/auth/msc3861_delegated.py +617 -0
  29. synapse/api/auth_blocking.py +144 -0
  30. synapse/api/constants.py +362 -0
  31. synapse/api/errors.py +907 -0
  32. synapse/api/filtering.py +539 -0
  33. synapse/api/presence.py +104 -0
  34. synapse/api/ratelimiting.py +482 -0
  35. synapse/api/room_versions.py +535 -0
  36. synapse/api/urls.py +119 -0
  37. synapse/app/__init__.py +60 -0
  38. synapse/app/_base.py +866 -0
  39. synapse/app/admin_cmd.py +388 -0
  40. synapse/app/appservice.py +30 -0
  41. synapse/app/client_reader.py +30 -0
  42. synapse/app/complement_fork_starter.py +206 -0
  43. synapse/app/event_creator.py +29 -0
  44. synapse/app/federation_reader.py +30 -0
  45. synapse/app/federation_sender.py +30 -0
  46. synapse/app/frontend_proxy.py +30 -0
  47. synapse/app/generic_worker.py +475 -0
  48. synapse/app/homeserver.py +504 -0
  49. synapse/app/media_repository.py +30 -0
  50. synapse/app/phone_stats_home.py +296 -0
  51. synapse/app/pusher.py +30 -0
  52. synapse/app/synchrotron.py +30 -0
  53. synapse/app/user_dir.py +31 -0
  54. synapse/appservice/__init__.py +461 -0
  55. synapse/appservice/api.py +569 -0
  56. synapse/appservice/scheduler.py +567 -0
  57. synapse/config/__init__.py +27 -0
  58. synapse/config/__main__.py +62 -0
  59. synapse/config/_base.py +1108 -0
  60. synapse/config/_base.pyi +217 -0
  61. synapse/config/_util.py +99 -0
  62. synapse/config/account_validity.py +116 -0
  63. synapse/config/api.py +141 -0
  64. synapse/config/appservice.py +210 -0
  65. synapse/config/auth.py +80 -0
  66. synapse/config/auto_accept_invites.py +43 -0
  67. synapse/config/background_updates.py +44 -0
  68. synapse/config/cache.py +231 -0
  69. synapse/config/captcha.py +90 -0
  70. synapse/config/cas.py +116 -0
  71. synapse/config/consent.py +73 -0
  72. synapse/config/database.py +184 -0
  73. synapse/config/emailconfig.py +367 -0
  74. synapse/config/experimental.py +595 -0
  75. synapse/config/federation.py +114 -0
  76. synapse/config/homeserver.py +141 -0
  77. synapse/config/jwt.py +55 -0
  78. synapse/config/key.py +447 -0
  79. synapse/config/logger.py +390 -0
  80. synapse/config/mas.py +191 -0
  81. synapse/config/matrixrtc.py +66 -0
  82. synapse/config/metrics.py +84 -0
  83. synapse/config/modules.py +40 -0
  84. synapse/config/oembed.py +185 -0
  85. synapse/config/oidc.py +509 -0
  86. synapse/config/password_auth_providers.py +82 -0
  87. synapse/config/push.py +64 -0
  88. synapse/config/ratelimiting.py +254 -0
  89. synapse/config/redis.py +74 -0
  90. synapse/config/registration.py +296 -0
  91. synapse/config/repository.py +311 -0
  92. synapse/config/retention.py +162 -0
  93. synapse/config/room.py +88 -0
  94. synapse/config/room_directory.py +165 -0
  95. synapse/config/saml2.py +251 -0
  96. synapse/config/server.py +1170 -0
  97. synapse/config/server_notices.py +84 -0
  98. synapse/config/spam_checker.py +66 -0
  99. synapse/config/sso.py +121 -0
  100. synapse/config/stats.py +54 -0
  101. synapse/config/third_party_event_rules.py +40 -0
  102. synapse/config/tls.py +192 -0
  103. synapse/config/tracer.py +71 -0
  104. synapse/config/user_directory.py +47 -0
  105. synapse/config/user_types.py +44 -0
  106. synapse/config/voip.py +59 -0
  107. synapse/config/workers.py +642 -0
  108. synapse/crypto/__init__.py +20 -0
  109. synapse/crypto/context_factory.py +278 -0
  110. synapse/crypto/event_signing.py +194 -0
  111. synapse/crypto/keyring.py +931 -0
  112. synapse/event_auth.py +1266 -0
  113. synapse/events/__init__.py +668 -0
  114. synapse/events/auto_accept_invites.py +216 -0
  115. synapse/events/builder.py +387 -0
  116. synapse/events/presence_router.py +245 -0
  117. synapse/events/snapshot.py +559 -0
  118. synapse/events/utils.py +928 -0
  119. synapse/events/validator.py +305 -0
  120. synapse/federation/__init__.py +22 -0
  121. synapse/federation/federation_base.py +383 -0
  122. synapse/federation/federation_client.py +2134 -0
  123. synapse/federation/federation_server.py +1544 -0
  124. synapse/federation/persistence.py +71 -0
  125. synapse/federation/send_queue.py +532 -0
  126. synapse/federation/sender/__init__.py +1165 -0
  127. synapse/federation/sender/per_destination_queue.py +884 -0
  128. synapse/federation/sender/transaction_manager.py +210 -0
  129. synapse/federation/transport/__init__.py +28 -0
  130. synapse/federation/transport/client.py +1201 -0
  131. synapse/federation/transport/server/__init__.py +334 -0
  132. synapse/federation/transport/server/_base.py +429 -0
  133. synapse/federation/transport/server/federation.py +912 -0
  134. synapse/federation/units.py +133 -0
  135. synapse/handlers/__init__.py +20 -0
  136. synapse/handlers/account.py +162 -0
  137. synapse/handlers/account_data.py +362 -0
  138. synapse/handlers/account_validity.py +361 -0
  139. synapse/handlers/admin.py +618 -0
  140. synapse/handlers/appservice.py +991 -0
  141. synapse/handlers/auth.py +2494 -0
  142. synapse/handlers/cas.py +413 -0
  143. synapse/handlers/deactivate_account.py +363 -0
  144. synapse/handlers/delayed_events.py +635 -0
  145. synapse/handlers/device.py +1873 -0
  146. synapse/handlers/devicemessage.py +399 -0
  147. synapse/handlers/directory.py +554 -0
  148. synapse/handlers/e2e_keys.py +1834 -0
  149. synapse/handlers/e2e_room_keys.py +455 -0
  150. synapse/handlers/event_auth.py +390 -0
  151. synapse/handlers/events.py +201 -0
  152. synapse/handlers/federation.py +2043 -0
  153. synapse/handlers/federation_event.py +2420 -0
  154. synapse/handlers/identity.py +812 -0
  155. synapse/handlers/initial_sync.py +528 -0
  156. synapse/handlers/jwt.py +120 -0
  157. synapse/handlers/message.py +2347 -0
  158. synapse/handlers/oidc.py +1803 -0
  159. synapse/handlers/pagination.py +768 -0
  160. synapse/handlers/password_policy.py +102 -0
  161. synapse/handlers/presence.py +2638 -0
  162. synapse/handlers/profile.py +655 -0
  163. synapse/handlers/push_rules.py +164 -0
  164. synapse/handlers/read_marker.py +79 -0
  165. synapse/handlers/receipts.py +351 -0
  166. synapse/handlers/register.py +1060 -0
  167. synapse/handlers/relations.py +624 -0
  168. synapse/handlers/reports.py +98 -0
  169. synapse/handlers/room.py +2447 -0
  170. synapse/handlers/room_list.py +632 -0
  171. synapse/handlers/room_member.py +2365 -0
  172. synapse/handlers/room_member_worker.py +146 -0
  173. synapse/handlers/room_policy.py +186 -0
  174. synapse/handlers/room_summary.py +1057 -0
  175. synapse/handlers/saml.py +524 -0
  176. synapse/handlers/search.py +723 -0
  177. synapse/handlers/send_email.py +209 -0
  178. synapse/handlers/set_password.py +71 -0
  179. synapse/handlers/sliding_sync/__init__.py +1701 -0
  180. synapse/handlers/sliding_sync/extensions.py +970 -0
  181. synapse/handlers/sliding_sync/room_lists.py +2266 -0
  182. synapse/handlers/sliding_sync/store.py +128 -0
  183. synapse/handlers/sso.py +1292 -0
  184. synapse/handlers/state_deltas.py +82 -0
  185. synapse/handlers/stats.py +322 -0
  186. synapse/handlers/sync.py +3109 -0
  187. synapse/handlers/thread_subscriptions.py +190 -0
  188. synapse/handlers/typing.py +606 -0
  189. synapse/handlers/ui_auth/__init__.py +48 -0
  190. synapse/handlers/ui_auth/checkers.py +332 -0
  191. synapse/handlers/user_directory.py +783 -0
  192. synapse/handlers/worker_lock.py +365 -0
  193. synapse/http/__init__.py +106 -0
  194. synapse/http/additional_resource.py +62 -0
  195. synapse/http/client.py +1360 -0
  196. synapse/http/connectproxyclient.py +309 -0
  197. synapse/http/federation/__init__.py +19 -0
  198. synapse/http/federation/matrix_federation_agent.py +490 -0
  199. synapse/http/federation/srv_resolver.py +196 -0
  200. synapse/http/federation/well_known_resolver.py +367 -0
  201. synapse/http/matrixfederationclient.py +1875 -0
  202. synapse/http/proxy.py +290 -0
  203. synapse/http/proxyagent.py +497 -0
  204. synapse/http/replicationagent.py +203 -0
  205. synapse/http/request_metrics.py +309 -0
  206. synapse/http/server.py +1114 -0
  207. synapse/http/servlet.py +1019 -0
  208. synapse/http/site.py +825 -0
  209. synapse/http/types.py +27 -0
  210. synapse/logging/__init__.py +31 -0
  211. synapse/logging/_remote.py +261 -0
  212. synapse/logging/_terse_json.py +95 -0
  213. synapse/logging/context.py +1211 -0
  214. synapse/logging/formatter.py +63 -0
  215. synapse/logging/handlers.py +99 -0
  216. synapse/logging/loggers.py +25 -0
  217. synapse/logging/opentracing.py +1132 -0
  218. synapse/logging/scopecontextmanager.py +161 -0
  219. synapse/media/_base.py +827 -0
  220. synapse/media/filepath.py +417 -0
  221. synapse/media/media_repository.py +1580 -0
  222. synapse/media/media_storage.py +704 -0
  223. synapse/media/oembed.py +277 -0
  224. synapse/media/preview_html.py +559 -0
  225. synapse/media/storage_provider.py +195 -0
  226. synapse/media/thumbnailer.py +833 -0
  227. synapse/media/url_previewer.py +875 -0
  228. synapse/metrics/__init__.py +754 -0
  229. synapse/metrics/_gc.py +219 -0
  230. synapse/metrics/_reactor_metrics.py +171 -0
  231. synapse/metrics/_types.py +38 -0
  232. synapse/metrics/background_process_metrics.py +556 -0
  233. synapse/metrics/common_usage_metrics.py +94 -0
  234. synapse/metrics/jemalloc.py +248 -0
  235. synapse/module_api/__init__.py +2154 -0
  236. synapse/module_api/callbacks/__init__.py +50 -0
  237. synapse/module_api/callbacks/account_validity_callbacks.py +106 -0
  238. synapse/module_api/callbacks/media_repository_callbacks.py +160 -0
  239. synapse/module_api/callbacks/ratelimit_callbacks.py +79 -0
  240. synapse/module_api/callbacks/spamchecker_callbacks.py +1113 -0
  241. synapse/module_api/callbacks/third_party_event_rules_callbacks.py +599 -0
  242. synapse/module_api/errors.py +42 -0
  243. synapse/notifier.py +972 -0
  244. synapse/push/__init__.py +212 -0
  245. synapse/push/bulk_push_rule_evaluator.py +637 -0
  246. synapse/push/clientformat.py +126 -0
  247. synapse/push/emailpusher.py +333 -0
  248. synapse/push/httppusher.py +564 -0
  249. synapse/push/mailer.py +1012 -0
  250. synapse/push/presentable_names.py +216 -0
  251. synapse/push/push_tools.py +114 -0
  252. synapse/push/push_types.py +141 -0
  253. synapse/push/pusher.py +87 -0
  254. synapse/push/pusherpool.py +501 -0
  255. synapse/push/rulekinds.py +33 -0
  256. synapse/py.typed +0 -0
  257. synapse/replication/__init__.py +20 -0
  258. synapse/replication/http/__init__.py +68 -0
  259. synapse/replication/http/_base.py +468 -0
  260. synapse/replication/http/account_data.py +297 -0
  261. synapse/replication/http/deactivate_account.py +81 -0
  262. synapse/replication/http/delayed_events.py +62 -0
  263. synapse/replication/http/devices.py +254 -0
  264. synapse/replication/http/federation.py +334 -0
  265. synapse/replication/http/login.py +106 -0
  266. synapse/replication/http/membership.py +364 -0
  267. synapse/replication/http/presence.py +133 -0
  268. synapse/replication/http/push.py +156 -0
  269. synapse/replication/http/register.py +172 -0
  270. synapse/replication/http/send_events.py +182 -0
  271. synapse/replication/http/state.py +82 -0
  272. synapse/replication/http/streams.py +101 -0
  273. synapse/replication/tcp/__init__.py +56 -0
  274. synapse/replication/tcp/client.py +552 -0
  275. synapse/replication/tcp/commands.py +569 -0
  276. synapse/replication/tcp/context.py +41 -0
  277. synapse/replication/tcp/external_cache.py +156 -0
  278. synapse/replication/tcp/handler.py +942 -0
  279. synapse/replication/tcp/protocol.py +608 -0
  280. synapse/replication/tcp/redis.py +509 -0
  281. synapse/replication/tcp/resource.py +348 -0
  282. synapse/replication/tcp/streams/__init__.py +96 -0
  283. synapse/replication/tcp/streams/_base.py +766 -0
  284. synapse/replication/tcp/streams/events.py +287 -0
  285. synapse/replication/tcp/streams/federation.py +92 -0
  286. synapse/replication/tcp/streams/partial_state.py +80 -0
  287. synapse/res/providers.json +29 -0
  288. synapse/res/templates/_base.html +29 -0
  289. synapse/res/templates/account_previously_renewed.html +6 -0
  290. synapse/res/templates/account_renewed.html +6 -0
  291. synapse/res/templates/add_threepid.html +8 -0
  292. synapse/res/templates/add_threepid.txt +6 -0
  293. synapse/res/templates/add_threepid_failure.html +7 -0
  294. synapse/res/templates/add_threepid_success.html +6 -0
  295. synapse/res/templates/already_in_use.html +12 -0
  296. synapse/res/templates/already_in_use.txt +10 -0
  297. synapse/res/templates/auth_success.html +21 -0
  298. synapse/res/templates/invalid_token.html +6 -0
  299. synapse/res/templates/mail-Element.css +7 -0
  300. synapse/res/templates/mail-Vector.css +7 -0
  301. synapse/res/templates/mail-expiry.css +4 -0
  302. synapse/res/templates/mail.css +156 -0
  303. synapse/res/templates/notice_expiry.html +46 -0
  304. synapse/res/templates/notice_expiry.txt +7 -0
  305. synapse/res/templates/notif.html +51 -0
  306. synapse/res/templates/notif.txt +22 -0
  307. synapse/res/templates/notif_mail.html +59 -0
  308. synapse/res/templates/notif_mail.txt +10 -0
  309. synapse/res/templates/password_reset.html +10 -0
  310. synapse/res/templates/password_reset.txt +7 -0
  311. synapse/res/templates/password_reset_confirmation.html +15 -0
  312. synapse/res/templates/password_reset_failure.html +7 -0
  313. synapse/res/templates/password_reset_success.html +6 -0
  314. synapse/res/templates/recaptcha.html +42 -0
  315. synapse/res/templates/registration.html +12 -0
  316. synapse/res/templates/registration.txt +10 -0
  317. synapse/res/templates/registration_failure.html +6 -0
  318. synapse/res/templates/registration_success.html +6 -0
  319. synapse/res/templates/registration_token.html +18 -0
  320. synapse/res/templates/room.html +33 -0
  321. synapse/res/templates/room.txt +9 -0
  322. synapse/res/templates/sso.css +129 -0
  323. synapse/res/templates/sso_account_deactivated.html +25 -0
  324. synapse/res/templates/sso_auth_account_details.html +186 -0
  325. synapse/res/templates/sso_auth_account_details.js +116 -0
  326. synapse/res/templates/sso_auth_bad_user.html +26 -0
  327. synapse/res/templates/sso_auth_confirm.html +27 -0
  328. synapse/res/templates/sso_auth_success.html +26 -0
  329. synapse/res/templates/sso_error.html +71 -0
  330. synapse/res/templates/sso_footer.html +19 -0
  331. synapse/res/templates/sso_login_idp_picker.html +60 -0
  332. synapse/res/templates/sso_new_user_consent.html +30 -0
  333. synapse/res/templates/sso_partial_profile.html +19 -0
  334. synapse/res/templates/sso_redirect_confirm.html +39 -0
  335. synapse/res/templates/style.css +33 -0
  336. synapse/res/templates/terms.html +27 -0
  337. synapse/rest/__init__.py +197 -0
  338. synapse/rest/admin/__init__.py +390 -0
  339. synapse/rest/admin/_base.py +72 -0
  340. synapse/rest/admin/background_updates.py +171 -0
  341. synapse/rest/admin/devices.py +221 -0
  342. synapse/rest/admin/event_reports.py +173 -0
  343. synapse/rest/admin/events.py +69 -0
  344. synapse/rest/admin/experimental_features.py +137 -0
  345. synapse/rest/admin/federation.py +243 -0
  346. synapse/rest/admin/media.py +540 -0
  347. synapse/rest/admin/registration_tokens.py +358 -0
  348. synapse/rest/admin/rooms.py +1061 -0
  349. synapse/rest/admin/scheduled_tasks.py +70 -0
  350. synapse/rest/admin/server_notice_servlet.py +132 -0
  351. synapse/rest/admin/statistics.py +132 -0
  352. synapse/rest/admin/username_available.py +58 -0
  353. synapse/rest/admin/users.py +1608 -0
  354. synapse/rest/client/__init__.py +20 -0
  355. synapse/rest/client/_base.py +113 -0
  356. synapse/rest/client/account.py +930 -0
  357. synapse/rest/client/account_data.py +319 -0
  358. synapse/rest/client/account_validity.py +103 -0
  359. synapse/rest/client/appservice_ping.py +125 -0
  360. synapse/rest/client/auth.py +218 -0
  361. synapse/rest/client/auth_metadata.py +122 -0
  362. synapse/rest/client/capabilities.py +121 -0
  363. synapse/rest/client/delayed_events.py +111 -0
  364. synapse/rest/client/devices.py +587 -0
  365. synapse/rest/client/directory.py +211 -0
  366. synapse/rest/client/events.py +116 -0
  367. synapse/rest/client/filter.py +112 -0
  368. synapse/rest/client/initial_sync.py +65 -0
  369. synapse/rest/client/keys.py +678 -0
  370. synapse/rest/client/knock.py +104 -0
  371. synapse/rest/client/login.py +754 -0
  372. synapse/rest/client/login_token_request.py +127 -0
  373. synapse/rest/client/logout.py +93 -0
  374. synapse/rest/client/matrixrtc.py +52 -0
  375. synapse/rest/client/media.py +286 -0
  376. synapse/rest/client/mutual_rooms.py +93 -0
  377. synapse/rest/client/notifications.py +137 -0
  378. synapse/rest/client/openid.py +109 -0
  379. synapse/rest/client/password_policy.py +69 -0
  380. synapse/rest/client/presence.py +131 -0
  381. synapse/rest/client/profile.py +291 -0
  382. synapse/rest/client/push_rule.py +331 -0
  383. synapse/rest/client/pusher.py +181 -0
  384. synapse/rest/client/read_marker.py +104 -0
  385. synapse/rest/client/receipts.py +165 -0
  386. synapse/rest/client/register.py +1067 -0
  387. synapse/rest/client/relations.py +138 -0
  388. synapse/rest/client/rendezvous.py +76 -0
  389. synapse/rest/client/reporting.py +207 -0
  390. synapse/rest/client/room.py +1669 -0
  391. synapse/rest/client/room_keys.py +426 -0
  392. synapse/rest/client/room_upgrade_rest_servlet.py +112 -0
  393. synapse/rest/client/sendtodevice.py +85 -0
  394. synapse/rest/client/sync.py +1131 -0
  395. synapse/rest/client/tags.py +129 -0
  396. synapse/rest/client/thirdparty.py +130 -0
  397. synapse/rest/client/thread_subscriptions.py +247 -0
  398. synapse/rest/client/tokenrefresh.py +52 -0
  399. synapse/rest/client/transactions.py +149 -0
  400. synapse/rest/client/user_directory.py +90 -0
  401. synapse/rest/client/versions.py +191 -0
  402. synapse/rest/client/voip.py +88 -0
  403. synapse/rest/consent/__init__.py +0 -0
  404. synapse/rest/consent/consent_resource.py +210 -0
  405. synapse/rest/health.py +38 -0
  406. synapse/rest/key/__init__.py +20 -0
  407. synapse/rest/key/v2/__init__.py +40 -0
  408. synapse/rest/key/v2/local_key_resource.py +125 -0
  409. synapse/rest/key/v2/remote_key_resource.py +302 -0
  410. synapse/rest/media/__init__.py +0 -0
  411. synapse/rest/media/config_resource.py +53 -0
  412. synapse/rest/media/create_resource.py +90 -0
  413. synapse/rest/media/download_resource.py +110 -0
  414. synapse/rest/media/media_repository_resource.py +113 -0
  415. synapse/rest/media/preview_url_resource.py +77 -0
  416. synapse/rest/media/thumbnail_resource.py +142 -0
  417. synapse/rest/media/upload_resource.py +187 -0
  418. synapse/rest/media/v1/__init__.py +39 -0
  419. synapse/rest/media/v1/_base.py +23 -0
  420. synapse/rest/media/v1/media_storage.py +23 -0
  421. synapse/rest/media/v1/storage_provider.py +23 -0
  422. synapse/rest/synapse/__init__.py +20 -0
  423. synapse/rest/synapse/client/__init__.py +93 -0
  424. synapse/rest/synapse/client/federation_whitelist.py +66 -0
  425. synapse/rest/synapse/client/jwks.py +77 -0
  426. synapse/rest/synapse/client/new_user_consent.py +115 -0
  427. synapse/rest/synapse/client/oidc/__init__.py +45 -0
  428. synapse/rest/synapse/client/oidc/backchannel_logout_resource.py +42 -0
  429. synapse/rest/synapse/client/oidc/callback_resource.py +48 -0
  430. synapse/rest/synapse/client/password_reset.py +129 -0
  431. synapse/rest/synapse/client/pick_idp.py +107 -0
  432. synapse/rest/synapse/client/pick_username.py +153 -0
  433. synapse/rest/synapse/client/rendezvous.py +58 -0
  434. synapse/rest/synapse/client/saml2/__init__.py +42 -0
  435. synapse/rest/synapse/client/saml2/metadata_resource.py +46 -0
  436. synapse/rest/synapse/client/saml2/response_resource.py +52 -0
  437. synapse/rest/synapse/client/sso_register.py +56 -0
  438. synapse/rest/synapse/client/unsubscribe.py +88 -0
  439. synapse/rest/synapse/mas/__init__.py +71 -0
  440. synapse/rest/synapse/mas/_base.py +55 -0
  441. synapse/rest/synapse/mas/devices.py +239 -0
  442. synapse/rest/synapse/mas/users.py +469 -0
  443. synapse/rest/well_known.py +148 -0
  444. synapse/server.py +1258 -0
  445. synapse/server_notices/__init__.py +0 -0
  446. synapse/server_notices/consent_server_notices.py +136 -0
  447. synapse/server_notices/resource_limits_server_notices.py +215 -0
  448. synapse/server_notices/server_notices_manager.py +388 -0
  449. synapse/server_notices/server_notices_sender.py +67 -0
  450. synapse/server_notices/worker_server_notices_sender.py +46 -0
  451. synapse/spam_checker_api/__init__.py +31 -0
  452. synapse/state/__init__.py +1022 -0
  453. synapse/state/v1.py +370 -0
  454. synapse/state/v2.py +985 -0
  455. synapse/static/client/login/index.html +47 -0
  456. synapse/static/client/login/js/jquery-3.4.1.min.js +2 -0
  457. synapse/static/client/login/js/login.js +291 -0
  458. synapse/static/client/login/spinner.gif +0 -0
  459. synapse/static/client/login/style.css +79 -0
  460. synapse/static/index.html +63 -0
  461. synapse/storage/__init__.py +43 -0
  462. synapse/storage/_base.py +245 -0
  463. synapse/storage/admin_client_config.py +26 -0
  464. synapse/storage/background_updates.py +1189 -0
  465. synapse/storage/controllers/__init__.py +57 -0
  466. synapse/storage/controllers/persist_events.py +1239 -0
  467. synapse/storage/controllers/purge_events.py +456 -0
  468. synapse/storage/controllers/state.py +954 -0
  469. synapse/storage/controllers/stats.py +119 -0
  470. synapse/storage/database.py +2720 -0
  471. synapse/storage/databases/__init__.py +175 -0
  472. synapse/storage/databases/main/__init__.py +424 -0
  473. synapse/storage/databases/main/account_data.py +1060 -0
  474. synapse/storage/databases/main/appservice.py +473 -0
  475. synapse/storage/databases/main/cache.py +911 -0
  476. synapse/storage/databases/main/censor_events.py +225 -0
  477. synapse/storage/databases/main/client_ips.py +817 -0
  478. synapse/storage/databases/main/delayed_events.py +560 -0
  479. synapse/storage/databases/main/deviceinbox.py +1272 -0
  480. synapse/storage/databases/main/devices.py +2581 -0
  481. synapse/storage/databases/main/directory.py +212 -0
  482. synapse/storage/databases/main/e2e_room_keys.py +690 -0
  483. synapse/storage/databases/main/end_to_end_keys.py +1896 -0
  484. synapse/storage/databases/main/event_federation.py +2509 -0
  485. synapse/storage/databases/main/event_push_actions.py +1937 -0
  486. synapse/storage/databases/main/events.py +3746 -0
  487. synapse/storage/databases/main/events_bg_updates.py +2910 -0
  488. synapse/storage/databases/main/events_forward_extremities.py +126 -0
  489. synapse/storage/databases/main/events_worker.py +2784 -0
  490. synapse/storage/databases/main/experimental_features.py +130 -0
  491. synapse/storage/databases/main/filtering.py +231 -0
  492. synapse/storage/databases/main/keys.py +291 -0
  493. synapse/storage/databases/main/lock.py +553 -0
  494. synapse/storage/databases/main/media_repository.py +1070 -0
  495. synapse/storage/databases/main/metrics.py +460 -0
  496. synapse/storage/databases/main/monthly_active_users.py +443 -0
  497. synapse/storage/databases/main/openid.py +61 -0
  498. synapse/storage/databases/main/presence.py +511 -0
  499. synapse/storage/databases/main/profile.py +541 -0
  500. synapse/storage/databases/main/purge_events.py +511 -0
  501. synapse/storage/databases/main/push_rule.py +972 -0
  502. synapse/storage/databases/main/pusher.py +794 -0
  503. synapse/storage/databases/main/receipts.py +1342 -0
  504. synapse/storage/databases/main/registration.py +3076 -0
  505. synapse/storage/databases/main/rejections.py +38 -0
  506. synapse/storage/databases/main/relations.py +1118 -0
  507. synapse/storage/databases/main/room.py +2781 -0
  508. synapse/storage/databases/main/roommember.py +2112 -0
  509. synapse/storage/databases/main/search.py +941 -0
  510. synapse/storage/databases/main/session.py +151 -0
  511. synapse/storage/databases/main/signatures.py +94 -0
  512. synapse/storage/databases/main/sliding_sync.py +603 -0
  513. synapse/storage/databases/main/state.py +1006 -0
  514. synapse/storage/databases/main/state_deltas.py +329 -0
  515. synapse/storage/databases/main/stats.py +791 -0
  516. synapse/storage/databases/main/stream.py +2580 -0
  517. synapse/storage/databases/main/tags.py +360 -0
  518. synapse/storage/databases/main/task_scheduler.py +225 -0
  519. synapse/storage/databases/main/thread_subscriptions.py +591 -0
  520. synapse/storage/databases/main/transactions.py +681 -0
  521. synapse/storage/databases/main/ui_auth.py +420 -0
  522. synapse/storage/databases/main/user_directory.py +1331 -0
  523. synapse/storage/databases/main/user_erasure_store.py +117 -0
  524. synapse/storage/databases/state/__init__.py +22 -0
  525. synapse/storage/databases/state/bg_updates.py +499 -0
  526. synapse/storage/databases/state/deletion.py +558 -0
  527. synapse/storage/databases/state/store.py +949 -0
  528. synapse/storage/engines/__init__.py +70 -0
  529. synapse/storage/engines/_base.py +154 -0
  530. synapse/storage/engines/postgres.py +261 -0
  531. synapse/storage/engines/sqlite.py +199 -0
  532. synapse/storage/invite_rule.py +112 -0
  533. synapse/storage/keys.py +40 -0
  534. synapse/storage/prepare_database.py +731 -0
  535. synapse/storage/push_rule.py +28 -0
  536. synapse/storage/roommember.py +89 -0
  537. synapse/storage/schema/README.md +4 -0
  538. synapse/storage/schema/__init__.py +182 -0
  539. synapse/storage/schema/common/delta/25/00background_updates.sql +40 -0
  540. synapse/storage/schema/common/delta/35/00background_updates_add_col.sql +36 -0
  541. synapse/storage/schema/common/delta/58/00background_update_ordering.sql +38 -0
  542. synapse/storage/schema/common/full_schemas/72/full.sql.postgres +8 -0
  543. synapse/storage/schema/common/full_schemas/72/full.sql.sqlite +6 -0
  544. synapse/storage/schema/common/schema_version.sql +60 -0
  545. synapse/storage/schema/main/delta/12/v12.sql +82 -0
  546. synapse/storage/schema/main/delta/13/v13.sql +38 -0
  547. synapse/storage/schema/main/delta/14/v14.sql +42 -0
  548. synapse/storage/schema/main/delta/15/appservice_txns.sql +50 -0
  549. synapse/storage/schema/main/delta/15/presence_indices.sql +2 -0
  550. synapse/storage/schema/main/delta/15/v15.sql +24 -0
  551. synapse/storage/schema/main/delta/16/events_order_index.sql +4 -0
  552. synapse/storage/schema/main/delta/16/remote_media_cache_index.sql +2 -0
  553. synapse/storage/schema/main/delta/16/remove_duplicates.sql +9 -0
  554. synapse/storage/schema/main/delta/16/room_alias_index.sql +3 -0
  555. synapse/storage/schema/main/delta/16/unique_constraints.sql +72 -0
  556. synapse/storage/schema/main/delta/16/users.sql +56 -0
  557. synapse/storage/schema/main/delta/17/drop_indexes.sql +37 -0
  558. synapse/storage/schema/main/delta/17/server_keys.sql +43 -0
  559. synapse/storage/schema/main/delta/17/user_threepids.sql +9 -0
  560. synapse/storage/schema/main/delta/18/server_keys_bigger_ints.sql +51 -0
  561. synapse/storage/schema/main/delta/19/event_index.sql +38 -0
  562. synapse/storage/schema/main/delta/20/dummy.sql +1 -0
  563. synapse/storage/schema/main/delta/20/pushers.py +93 -0
  564. synapse/storage/schema/main/delta/21/end_to_end_keys.sql +53 -0
  565. synapse/storage/schema/main/delta/21/receipts.sql +57 -0
  566. synapse/storage/schema/main/delta/22/receipts_index.sql +41 -0
  567. synapse/storage/schema/main/delta/22/user_threepids_unique.sql +19 -0
  568. synapse/storage/schema/main/delta/24/stats_reporting.sql +37 -0
  569. synapse/storage/schema/main/delta/25/fts.py +81 -0
  570. synapse/storage/schema/main/delta/25/guest_access.sql +44 -0
  571. synapse/storage/schema/main/delta/25/history_visibility.sql +44 -0
  572. synapse/storage/schema/main/delta/25/tags.sql +57 -0
  573. synapse/storage/schema/main/delta/26/account_data.sql +36 -0
  574. synapse/storage/schema/main/delta/27/account_data.sql +55 -0
  575. synapse/storage/schema/main/delta/27/forgotten_memberships.sql +45 -0
  576. synapse/storage/schema/main/delta/27/ts.py +61 -0
  577. synapse/storage/schema/main/delta/28/event_push_actions.sql +46 -0
  578. synapse/storage/schema/main/delta/28/events_room_stream.sql +39 -0
  579. synapse/storage/schema/main/delta/28/public_roms_index.sql +39 -0
  580. synapse/storage/schema/main/delta/28/receipts_user_id_index.sql +41 -0
  581. synapse/storage/schema/main/delta/28/upgrade_times.sql +40 -0
  582. synapse/storage/schema/main/delta/28/users_is_guest.sql +41 -0
  583. synapse/storage/schema/main/delta/29/push_actions.sql +54 -0
  584. synapse/storage/schema/main/delta/30/alias_creator.sql +35 -0
  585. synapse/storage/schema/main/delta/30/as_users.py +82 -0
  586. synapse/storage/schema/main/delta/30/deleted_pushers.sql +44 -0
  587. synapse/storage/schema/main/delta/30/presence_stream.sql +49 -0
  588. synapse/storage/schema/main/delta/30/public_rooms.sql +42 -0
  589. synapse/storage/schema/main/delta/30/push_rule_stream.sql +57 -0
  590. synapse/storage/schema/main/delta/30/threepid_guest_access_tokens.sql +43 -0
  591. synapse/storage/schema/main/delta/31/invites.sql +61 -0
  592. synapse/storage/schema/main/delta/31/local_media_repository_url_cache.sql +46 -0
  593. synapse/storage/schema/main/delta/31/pushers_0.py +92 -0
  594. synapse/storage/schema/main/delta/31/pushers_index.sql +41 -0
  595. synapse/storage/schema/main/delta/31/search_update.py +65 -0
  596. synapse/storage/schema/main/delta/32/events.sql +35 -0
  597. synapse/storage/schema/main/delta/32/openid.sql +9 -0
  598. synapse/storage/schema/main/delta/32/pusher_throttle.sql +42 -0
  599. synapse/storage/schema/main/delta/32/remove_indices.sql +52 -0
  600. synapse/storage/schema/main/delta/32/reports.sql +44 -0
  601. synapse/storage/schema/main/delta/33/access_tokens_device_index.sql +36 -0
  602. synapse/storage/schema/main/delta/33/devices.sql +40 -0
  603. synapse/storage/schema/main/delta/33/devices_for_e2e_keys.sql +38 -0
  604. synapse/storage/schema/main/delta/33/devices_for_e2e_keys_clear_unknown_device.sql +39 -0
  605. synapse/storage/schema/main/delta/33/event_fields.py +61 -0
  606. synapse/storage/schema/main/delta/33/remote_media_ts.py +43 -0
  607. synapse/storage/schema/main/delta/33/user_ips_index.sql +36 -0
  608. synapse/storage/schema/main/delta/34/appservice_stream.sql +42 -0
  609. synapse/storage/schema/main/delta/34/cache_stream.py +50 -0
  610. synapse/storage/schema/main/delta/34/device_inbox.sql +43 -0
  611. synapse/storage/schema/main/delta/34/push_display_name_rename.sql +39 -0
  612. synapse/storage/schema/main/delta/34/received_txn_purge.py +36 -0
  613. synapse/storage/schema/main/delta/35/contains_url.sql +36 -0
  614. synapse/storage/schema/main/delta/35/device_outbox.sql +58 -0
  615. synapse/storage/schema/main/delta/35/device_stream_id.sql +40 -0
  616. synapse/storage/schema/main/delta/35/event_push_actions_index.sql +36 -0
  617. synapse/storage/schema/main/delta/35/public_room_list_change_stream.sql +52 -0
  618. synapse/storage/schema/main/delta/35/stream_order_to_extrem.sql +56 -0
  619. synapse/storage/schema/main/delta/36/readd_public_rooms.sql +45 -0
  620. synapse/storage/schema/main/delta/37/remove_auth_idx.py +89 -0
  621. synapse/storage/schema/main/delta/37/user_threepids.sql +71 -0
  622. synapse/storage/schema/main/delta/38/postgres_fts_gist.sql +38 -0
  623. synapse/storage/schema/main/delta/39/appservice_room_list.sql +48 -0
  624. synapse/storage/schema/main/delta/39/device_federation_stream_idx.sql +35 -0
  625. synapse/storage/schema/main/delta/39/event_push_index.sql +36 -0
  626. synapse/storage/schema/main/delta/39/federation_out_position.sql +41 -0
  627. synapse/storage/schema/main/delta/39/membership_profile.sql +39 -0
  628. synapse/storage/schema/main/delta/40/current_state_idx.sql +36 -0
  629. synapse/storage/schema/main/delta/40/device_inbox.sql +40 -0
  630. synapse/storage/schema/main/delta/40/device_list_streams.sql +79 -0
  631. synapse/storage/schema/main/delta/40/event_push_summary.sql +57 -0
  632. synapse/storage/schema/main/delta/40/pushers.sql +58 -0
  633. synapse/storage/schema/main/delta/41/device_list_stream_idx.sql +36 -0
  634. synapse/storage/schema/main/delta/41/device_outbound_index.sql +35 -0
  635. synapse/storage/schema/main/delta/41/event_search_event_id_idx.sql +36 -0
  636. synapse/storage/schema/main/delta/41/ratelimit.sql +41 -0
  637. synapse/storage/schema/main/delta/42/current_state_delta.sql +48 -0
  638. synapse/storage/schema/main/delta/42/device_list_last_id.sql +52 -0
  639. synapse/storage/schema/main/delta/42/event_auth_state_only.sql +36 -0
  640. synapse/storage/schema/main/delta/42/user_dir.py +88 -0
  641. synapse/storage/schema/main/delta/43/blocked_rooms.sql +40 -0
  642. synapse/storage/schema/main/delta/43/quarantine_media.sql +36 -0
  643. synapse/storage/schema/main/delta/43/url_cache.sql +35 -0
  644. synapse/storage/schema/main/delta/43/user_share.sql +52 -0
  645. synapse/storage/schema/main/delta/44/expire_url_cache.sql +60 -0
  646. synapse/storage/schema/main/delta/45/group_server.sql +186 -0
  647. synapse/storage/schema/main/delta/45/profile_cache.sql +47 -0
  648. synapse/storage/schema/main/delta/46/drop_refresh_tokens.sql +36 -0
  649. synapse/storage/schema/main/delta/46/drop_unique_deleted_pushers.sql +54 -0
  650. synapse/storage/schema/main/delta/46/group_server.sql +51 -0
  651. synapse/storage/schema/main/delta/46/local_media_repository_url_idx.sql +43 -0
  652. synapse/storage/schema/main/delta/46/user_dir_null_room_ids.sql +54 -0
  653. synapse/storage/schema/main/delta/46/user_dir_typos.sql +43 -0
  654. synapse/storage/schema/main/delta/47/last_access_media.sql +35 -0
  655. synapse/storage/schema/main/delta/47/postgres_fts_gin.sql +36 -0
  656. synapse/storage/schema/main/delta/47/push_actions_staging.sql +47 -0
  657. synapse/storage/schema/main/delta/48/add_user_consent.sql +37 -0
  658. synapse/storage/schema/main/delta/48/add_user_ips_last_seen_index.sql +36 -0
  659. synapse/storage/schema/main/delta/48/deactivated_users.sql +44 -0
  660. synapse/storage/schema/main/delta/48/group_unique_indexes.py +67 -0
  661. synapse/storage/schema/main/delta/48/groups_joinable.sql +41 -0
  662. synapse/storage/schema/main/delta/49/add_user_consent_server_notice_sent.sql +39 -0
  663. synapse/storage/schema/main/delta/49/add_user_daily_visits.sql +40 -0
  664. synapse/storage/schema/main/delta/49/add_user_ips_last_seen_only_index.sql +36 -0
  665. synapse/storage/schema/main/delta/50/add_creation_ts_users_index.sql +38 -0
  666. synapse/storage/schema/main/delta/50/erasure_store.sql +40 -0
  667. synapse/storage/schema/main/delta/50/make_event_content_nullable.py +102 -0
  668. synapse/storage/schema/main/delta/51/e2e_room_keys.sql +58 -0
  669. synapse/storage/schema/main/delta/51/monthly_active_users.sql +46 -0
  670. synapse/storage/schema/main/delta/52/add_event_to_state_group_index.sql +38 -0
  671. synapse/storage/schema/main/delta/52/device_list_streams_unique_idx.sql +55 -0
  672. synapse/storage/schema/main/delta/52/e2e_room_keys.sql +72 -0
  673. synapse/storage/schema/main/delta/53/add_user_type_to_users.sql +38 -0
  674. synapse/storage/schema/main/delta/53/drop_sent_transactions.sql +35 -0
  675. synapse/storage/schema/main/delta/53/event_format_version.sql +35 -0
  676. synapse/storage/schema/main/delta/53/user_dir_populate.sql +49 -0
  677. synapse/storage/schema/main/delta/53/user_ips_index.sql +49 -0
  678. synapse/storage/schema/main/delta/53/user_share.sql +63 -0
  679. synapse/storage/schema/main/delta/53/user_threepid_id.sql +48 -0
  680. synapse/storage/schema/main/delta/53/users_in_public_rooms.sql +47 -0
  681. synapse/storage/schema/main/delta/54/account_validity_with_renewal.sql +49 -0
  682. synapse/storage/schema/main/delta/54/add_validity_to_server_keys.sql +42 -0
  683. synapse/storage/schema/main/delta/54/delete_forward_extremities.sql +42 -0
  684. synapse/storage/schema/main/delta/54/drop_legacy_tables.sql +49 -0
  685. synapse/storage/schema/main/delta/54/drop_presence_list.sql +35 -0
  686. synapse/storage/schema/main/delta/54/relations.sql +46 -0
  687. synapse/storage/schema/main/delta/54/stats.sql +99 -0
  688. synapse/storage/schema/main/delta/54/stats2.sql +47 -0
  689. synapse/storage/schema/main/delta/55/access_token_expiry.sql +37 -0
  690. synapse/storage/schema/main/delta/55/track_threepid_validations.sql +50 -0
  691. synapse/storage/schema/main/delta/55/users_alter_deactivated.sql +38 -0
  692. synapse/storage/schema/main/delta/56/add_spans_to_device_lists.sql +39 -0
  693. synapse/storage/schema/main/delta/56/current_state_events_membership.sql +41 -0
  694. synapse/storage/schema/main/delta/56/current_state_events_membership_mk2.sql +43 -0
  695. synapse/storage/schema/main/delta/56/delete_keys_from_deleted_backups.sql +44 -0
  696. synapse/storage/schema/main/delta/56/destinations_failure_ts.sql +44 -0
  697. synapse/storage/schema/main/delta/56/destinations_retry_interval_type.sql.postgres +18 -0
  698. synapse/storage/schema/main/delta/56/device_stream_id_insert.sql +39 -0
  699. synapse/storage/schema/main/delta/56/devices_last_seen.sql +43 -0
  700. synapse/storage/schema/main/delta/56/drop_unused_event_tables.sql +39 -0
  701. synapse/storage/schema/main/delta/56/event_expiry.sql +40 -0
  702. synapse/storage/schema/main/delta/56/event_labels.sql +49 -0
  703. synapse/storage/schema/main/delta/56/event_labels_background_update.sql +36 -0
  704. synapse/storage/schema/main/delta/56/fix_room_keys_index.sql +37 -0
  705. synapse/storage/schema/main/delta/56/hidden_devices.sql +37 -0
  706. synapse/storage/schema/main/delta/56/hidden_devices_fix.sql.sqlite +42 -0
  707. synapse/storage/schema/main/delta/56/nuke_empty_communities_from_db.sql +48 -0
  708. synapse/storage/schema/main/delta/56/public_room_list_idx.sql +35 -0
  709. synapse/storage/schema/main/delta/56/redaction_censor.sql +35 -0
  710. synapse/storage/schema/main/delta/56/redaction_censor2.sql +41 -0
  711. synapse/storage/schema/main/delta/56/redaction_censor3_fix_update.sql.postgres +25 -0
  712. synapse/storage/schema/main/delta/56/redaction_censor4.sql +35 -0
  713. synapse/storage/schema/main/delta/56/remove_tombstoned_rooms_from_directory.sql +38 -0
  714. synapse/storage/schema/main/delta/56/room_key_etag.sql +36 -0
  715. synapse/storage/schema/main/delta/56/room_membership_idx.sql +37 -0
  716. synapse/storage/schema/main/delta/56/room_retention.sql +52 -0
  717. synapse/storage/schema/main/delta/56/signing_keys.sql +75 -0
  718. synapse/storage/schema/main/delta/56/signing_keys_nonunique_signatures.sql +41 -0
  719. synapse/storage/schema/main/delta/56/stats_separated.sql +175 -0
  720. synapse/storage/schema/main/delta/56/unique_user_filter_index.py +46 -0
  721. synapse/storage/schema/main/delta/56/user_external_ids.sql +43 -0
  722. synapse/storage/schema/main/delta/56/users_in_public_rooms_idx.sql +36 -0
  723. synapse/storage/schema/main/delta/57/delete_old_current_state_events.sql +41 -0
  724. synapse/storage/schema/main/delta/57/device_list_remote_cache_stale.sql +44 -0
  725. synapse/storage/schema/main/delta/57/local_current_membership.py +111 -0
  726. synapse/storage/schema/main/delta/57/remove_sent_outbound_pokes.sql +40 -0
  727. synapse/storage/schema/main/delta/57/rooms_version_column.sql +43 -0
  728. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.postgres +35 -0
  729. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.sqlite +22 -0
  730. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.postgres +39 -0
  731. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.sqlite +23 -0
  732. synapse/storage/schema/main/delta/58/02remove_dup_outbound_pokes.sql +41 -0
  733. synapse/storage/schema/main/delta/58/03persist_ui_auth.sql +55 -0
  734. synapse/storage/schema/main/delta/58/05cache_instance.sql.postgres +30 -0
  735. synapse/storage/schema/main/delta/58/06dlols_unique_idx.py +83 -0
  736. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.postgres +33 -0
  737. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.sqlite +44 -0
  738. synapse/storage/schema/main/delta/58/07persist_ui_auth_ips.sql +44 -0
  739. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.postgres +18 -0
  740. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.sqlite +18 -0
  741. synapse/storage/schema/main/delta/58/09shadow_ban.sql +37 -0
  742. synapse/storage/schema/main/delta/58/10_pushrules_enabled_delete_obsolete.sql +47 -0
  743. synapse/storage/schema/main/delta/58/10drop_local_rejections_stream.sql +41 -0
  744. synapse/storage/schema/main/delta/58/10federation_pos_instance_name.sql +41 -0
  745. synapse/storage/schema/main/delta/58/11dehydration.sql +39 -0
  746. synapse/storage/schema/main/delta/58/11fallback.sql +43 -0
  747. synapse/storage/schema/main/delta/58/11user_id_seq.py +38 -0
  748. synapse/storage/schema/main/delta/58/12room_stats.sql +51 -0
  749. synapse/storage/schema/main/delta/58/13remove_presence_allow_inbound.sql +36 -0
  750. synapse/storage/schema/main/delta/58/14events_instance_name.sql +35 -0
  751. synapse/storage/schema/main/delta/58/14events_instance_name.sql.postgres +28 -0
  752. synapse/storage/schema/main/delta/58/15_catchup_destination_rooms.sql +61 -0
  753. synapse/storage/schema/main/delta/58/15unread_count.sql +45 -0
  754. synapse/storage/schema/main/delta/58/16populate_stats_process_rooms_fix.sql +41 -0
  755. synapse/storage/schema/main/delta/58/17_catchup_last_successful.sql +40 -0
  756. synapse/storage/schema/main/delta/58/18stream_positions.sql +41 -0
  757. synapse/storage/schema/main/delta/58/19instance_map.sql.postgres +25 -0
  758. synapse/storage/schema/main/delta/58/19txn_id.sql +59 -0
  759. synapse/storage/schema/main/delta/58/20instance_name_event_tables.sql +36 -0
  760. synapse/storage/schema/main/delta/58/20user_daily_visits.sql +37 -0
  761. synapse/storage/schema/main/delta/58/21as_device_stream.sql +36 -0
  762. synapse/storage/schema/main/delta/58/21drop_device_max_stream_id.sql +1 -0
  763. synapse/storage/schema/main/delta/58/22puppet_token.sql +36 -0
  764. synapse/storage/schema/main/delta/58/22users_have_local_media.sql +2 -0
  765. synapse/storage/schema/main/delta/58/23e2e_cross_signing_keys_idx.sql +36 -0
  766. synapse/storage/schema/main/delta/58/24drop_event_json_index.sql +38 -0
  767. synapse/storage/schema/main/delta/58/25user_external_ids_user_id_idx.sql +36 -0
  768. synapse/storage/schema/main/delta/58/26access_token_last_validated.sql +37 -0
  769. synapse/storage/schema/main/delta/58/27local_invites.sql +37 -0
  770. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.postgres +16 -0
  771. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.sqlite +62 -0
  772. synapse/storage/schema/main/delta/59/01ignored_user.py +85 -0
  773. synapse/storage/schema/main/delta/59/02shard_send_to_device.sql +37 -0
  774. synapse/storage/schema/main/delta/59/03shard_send_to_device_sequence.sql.postgres +25 -0
  775. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql +71 -0
  776. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql.postgres +16 -0
  777. synapse/storage/schema/main/delta/59/04drop_account_data.sql +36 -0
  778. synapse/storage/schema/main/delta/59/05cache_invalidation.sql +36 -0
  779. synapse/storage/schema/main/delta/59/06chain_cover_index.sql +36 -0
  780. synapse/storage/schema/main/delta/59/06shard_account_data.sql +39 -0
  781. synapse/storage/schema/main/delta/59/06shard_account_data.sql.postgres +32 -0
  782. synapse/storage/schema/main/delta/59/07shard_account_data_fix.sql +37 -0
  783. synapse/storage/schema/main/delta/59/08delete_pushers_for_deactivated_accounts.sql +39 -0
  784. synapse/storage/schema/main/delta/59/08delete_stale_pushers.sql +39 -0
  785. synapse/storage/schema/main/delta/59/09rejected_events_metadata.sql +45 -0
  786. synapse/storage/schema/main/delta/59/10delete_purged_chain_cover.sql +36 -0
  787. synapse/storage/schema/main/delta/59/11add_knock_members_to_stats.sql +39 -0
  788. synapse/storage/schema/main/delta/59/11drop_thumbnail_constraint.sql.postgres +22 -0
  789. synapse/storage/schema/main/delta/59/12account_validity_token_used_ts_ms.sql +37 -0
  790. synapse/storage/schema/main/delta/59/12presence_stream_instance.sql +37 -0
  791. synapse/storage/schema/main/delta/59/12presence_stream_instance_seq.sql.postgres +20 -0
  792. synapse/storage/schema/main/delta/59/13users_to_send_full_presence_to.sql +53 -0
  793. synapse/storage/schema/main/delta/59/14refresh_tokens.sql +53 -0
  794. synapse/storage/schema/main/delta/59/15locks.sql +56 -0
  795. synapse/storage/schema/main/delta/59/16federation_inbound_staging.sql +51 -0
  796. synapse/storage/schema/main/delta/60/01recreate_stream_ordering.sql.postgres +45 -0
  797. synapse/storage/schema/main/delta/60/02change_stream_ordering_columns.sql.postgres +30 -0
  798. synapse/storage/schema/main/delta/61/01change_appservices_txns.sql.postgres +23 -0
  799. synapse/storage/schema/main/delta/61/01insertion_event_lookups.sql +68 -0
  800. synapse/storage/schema/main/delta/61/02drop_redundant_room_depth_index.sql +37 -0
  801. synapse/storage/schema/main/delta/61/03recreate_min_depth.py +74 -0
  802. synapse/storage/schema/main/delta/62/01insertion_event_extremities.sql +43 -0
  803. synapse/storage/schema/main/delta/63/01create_registration_tokens.sql +42 -0
  804. synapse/storage/schema/main/delta/63/02delete_unlinked_email_pushers.sql +39 -0
  805. synapse/storage/schema/main/delta/63/02populate-rooms-creator.sql +36 -0
  806. synapse/storage/schema/main/delta/63/03session_store.sql +42 -0
  807. synapse/storage/schema/main/delta/63/04add_presence_stream_not_offline_index.sql +37 -0
  808. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.postgres +23 -0
  809. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.sqlite +37 -0
  810. synapse/storage/schema/main/delta/65/01msc2716_insertion_event_edges.sql +38 -0
  811. synapse/storage/schema/main/delta/65/03remove_hidden_devices_from_device_inbox.sql +41 -0
  812. synapse/storage/schema/main/delta/65/04_local_group_updates.sql +37 -0
  813. synapse/storage/schema/main/delta/65/05_remove_room_stats_historical_and_user_stats_historical.sql +38 -0
  814. synapse/storage/schema/main/delta/65/06remove_deleted_devices_from_device_inbox.sql +53 -0
  815. synapse/storage/schema/main/delta/65/07_arbitrary_relations.sql +37 -0
  816. synapse/storage/schema/main/delta/65/08_device_inbox_background_updates.sql +37 -0
  817. synapse/storage/schema/main/delta/65/10_expirable_refresh_tokens.sql +47 -0
  818. synapse/storage/schema/main/delta/65/11_devices_auth_provider_session.sql +46 -0
  819. synapse/storage/schema/main/delta/67/01drop_public_room_list_stream.sql +37 -0
  820. synapse/storage/schema/main/delta/68/01event_columns.sql +45 -0
  821. synapse/storage/schema/main/delta/68/02_msc2409_add_device_id_appservice_stream_type.sql +40 -0
  822. synapse/storage/schema/main/delta/68/03_delete_account_data_for_deactivated_accounts.sql +39 -0
  823. synapse/storage/schema/main/delta/68/04_refresh_tokens_index_next_token_id.sql +47 -0
  824. synapse/storage/schema/main/delta/68/04partial_state_rooms.sql +60 -0
  825. synapse/storage/schema/main/delta/68/05_delete_non_strings_from_event_search.sql.sqlite +22 -0
  826. synapse/storage/schema/main/delta/68/05partial_state_rooms_triggers.py +80 -0
  827. synapse/storage/schema/main/delta/68/06_msc3202_add_device_list_appservice_stream_type.sql +42 -0
  828. synapse/storage/schema/main/delta/69/01as_txn_seq.py +54 -0
  829. synapse/storage/schema/main/delta/69/01device_list_oubound_by_room.sql +57 -0
  830. synapse/storage/schema/main/delta/69/02cache_invalidation_index.sql +37 -0
  831. synapse/storage/schema/main/delta/70/01clean_table_purged_rooms.sql +39 -0
  832. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.postgres +43 -0
  833. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.sqlite +47 -0
  834. synapse/storage/schema/main/delta/71/01remove_noop_background_updates.sql +80 -0
  835. synapse/storage/schema/main/delta/71/02event_push_summary_unique.sql +37 -0
  836. synapse/storage/schema/main/delta/72/01add_room_type_to_state_stats.sql +38 -0
  837. synapse/storage/schema/main/delta/72/01event_push_summary_receipt.sql +54 -0
  838. synapse/storage/schema/main/delta/72/02event_push_actions_index.sql +38 -0
  839. synapse/storage/schema/main/delta/72/03bg_populate_events_columns.py +57 -0
  840. synapse/storage/schema/main/delta/72/03drop_event_reference_hashes.sql +36 -0
  841. synapse/storage/schema/main/delta/72/03remove_groups.sql +50 -0
  842. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.postgres +17 -0
  843. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.sqlite +40 -0
  844. synapse/storage/schema/main/delta/72/05receipts_event_stream_ordering.sql +38 -0
  845. synapse/storage/schema/main/delta/72/05remove_unstable_private_read_receipts.sql +38 -0
  846. synapse/storage/schema/main/delta/72/06add_consent_ts_to_users.sql +35 -0
  847. synapse/storage/schema/main/delta/72/06thread_notifications.sql +49 -0
  848. synapse/storage/schema/main/delta/72/07force_update_current_state_events_membership.py +67 -0
  849. synapse/storage/schema/main/delta/72/07thread_receipts.sql.postgres +30 -0
  850. synapse/storage/schema/main/delta/72/07thread_receipts.sql.sqlite +70 -0
  851. synapse/storage/schema/main/delta/72/08begin_cache_invalidation_seq_at_2.sql.postgres +23 -0
  852. synapse/storage/schema/main/delta/72/08thread_receipts.sql +39 -0
  853. synapse/storage/schema/main/delta/72/09partial_indices.sql.sqlite +56 -0
  854. synapse/storage/schema/main/delta/73/01event_failed_pull_attempts.sql +48 -0
  855. synapse/storage/schema/main/delta/73/02add_pusher_enabled.sql +35 -0
  856. synapse/storage/schema/main/delta/73/02room_id_indexes_for_purging.sql +41 -0
  857. synapse/storage/schema/main/delta/73/03pusher_device_id.sql +39 -0
  858. synapse/storage/schema/main/delta/73/03users_approved_column.sql +39 -0
  859. synapse/storage/schema/main/delta/73/04partial_join_details.sql +42 -0
  860. synapse/storage/schema/main/delta/73/04pending_device_list_updates.sql +47 -0
  861. synapse/storage/schema/main/delta/73/05old_push_actions.sql.postgres +22 -0
  862. synapse/storage/schema/main/delta/73/05old_push_actions.sql.sqlite +24 -0
  863. synapse/storage/schema/main/delta/73/06thread_notifications_thread_id_idx.sql +42 -0
  864. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.postgres +23 -0
  865. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.sqlite +76 -0
  866. synapse/storage/schema/main/delta/73/09partial_joined_via_destination.sql +37 -0
  867. synapse/storage/schema/main/delta/73/09threads_table.sql +49 -0
  868. synapse/storage/schema/main/delta/73/10_update_sqlite_fts4_tokenizer.py +71 -0
  869. synapse/storage/schema/main/delta/73/10login_tokens.sql +54 -0
  870. synapse/storage/schema/main/delta/73/11event_search_room_id_n_distinct.sql.postgres +33 -0
  871. synapse/storage/schema/main/delta/73/12refactor_device_list_outbound_pokes.sql +72 -0
  872. synapse/storage/schema/main/delta/73/13add_device_lists_index.sql +39 -0
  873. synapse/storage/schema/main/delta/73/20_un_partial_stated_room_stream.sql +51 -0
  874. synapse/storage/schema/main/delta/73/21_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  875. synapse/storage/schema/main/delta/73/22_rebuild_user_dir_stats.sql +48 -0
  876. synapse/storage/schema/main/delta/73/22_un_partial_stated_event_stream.sql +53 -0
  877. synapse/storage/schema/main/delta/73/23_fix_thread_index.sql +52 -0
  878. synapse/storage/schema/main/delta/73/23_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  879. synapse/storage/schema/main/delta/73/24_events_jump_to_date_index.sql +36 -0
  880. synapse/storage/schema/main/delta/73/25drop_presence.sql +36 -0
  881. synapse/storage/schema/main/delta/74/01_user_directory_stale_remote_users.sql +58 -0
  882. synapse/storage/schema/main/delta/74/02_set_device_id_for_pushers_bg_update.sql +38 -0
  883. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.postgres +29 -0
  884. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.sqlite +23 -0
  885. synapse/storage/schema/main/delta/74/03_room_membership_index.sql +38 -0
  886. synapse/storage/schema/main/delta/74/04_delete_e2e_backup_keys_for_deactivated_users.sql +36 -0
  887. synapse/storage/schema/main/delta/74/04_membership_tables_event_stream_ordering_triggers.py +87 -0
  888. synapse/storage/schema/main/delta/74/05_events_txn_id_device_id.sql +72 -0
  889. synapse/storage/schema/main/delta/74/90COMMENTS_destinations.sql.postgres +52 -0
  890. synapse/storage/schema/main/delta/76/01_add_profiles_full_user_id_column.sql +39 -0
  891. synapse/storage/schema/main/delta/76/02_add_user_filters_full_user_id_column.sql +39 -0
  892. synapse/storage/schema/main/delta/76/03_per_user_experimental_features.sql +46 -0
  893. synapse/storage/schema/main/delta/76/04_add_room_forgetter.sql +43 -0
  894. synapse/storage/schema/main/delta/77/01_add_profiles_not_valid_check.sql.postgres +16 -0
  895. synapse/storage/schema/main/delta/77/02_add_user_filters_not_valid_check.sql.postgres +16 -0
  896. synapse/storage/schema/main/delta/77/03bg_populate_full_user_id_profiles.sql +35 -0
  897. synapse/storage/schema/main/delta/77/04bg_populate_full_user_id_user_filters.sql +35 -0
  898. synapse/storage/schema/main/delta/77/05thread_notifications_backfill.sql +67 -0
  899. synapse/storage/schema/main/delta/77/06thread_notifications_not_null.sql.sqlite +102 -0
  900. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions.sql.postgres +27 -0
  901. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions_staging.sql.postgres +27 -0
  902. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_summary.sql.postgres +29 -0
  903. synapse/storage/schema/main/delta/77/14bg_indices_event_stream_ordering.sql +39 -0
  904. synapse/storage/schema/main/delta/78/01_validate_and_update_profiles.py +99 -0
  905. synapse/storage/schema/main/delta/78/02_validate_and_update_user_filters.py +100 -0
  906. synapse/storage/schema/main/delta/78/03_remove_unused_indexes_user_filters.py +72 -0
  907. synapse/storage/schema/main/delta/78/03event_extremities_constraints.py +65 -0
  908. synapse/storage/schema/main/delta/78/04_add_full_user_id_index_user_filters.py +32 -0
  909. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.postgres +102 -0
  910. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.sqlite +72 -0
  911. synapse/storage/schema/main/delta/79/04_mitigate_stream_ordering_update_race.py +70 -0
  912. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.postgres +69 -0
  913. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.sqlite +65 -0
  914. synapse/storage/schema/main/delta/80/01_users_alter_locked.sql +35 -0
  915. synapse/storage/schema/main/delta/80/02_read_write_locks_unlogged.sql.postgres +30 -0
  916. synapse/storage/schema/main/delta/80/02_scheduled_tasks.sql +47 -0
  917. synapse/storage/schema/main/delta/80/03_read_write_locks_triggers.sql.postgres +37 -0
  918. synapse/storage/schema/main/delta/80/04_read_write_locks_deadlock.sql.postgres +71 -0
  919. synapse/storage/schema/main/delta/82/02_scheduled_tasks_index.sql +35 -0
  920. synapse/storage/schema/main/delta/82/04_add_indices_for_purging_rooms.sql +39 -0
  921. synapse/storage/schema/main/delta/82/05gaps.sql +44 -0
  922. synapse/storage/schema/main/delta/83/01_drop_old_tables.sql +43 -0
  923. synapse/storage/schema/main/delta/83/03_instance_name_receipts.sql.sqlite +17 -0
  924. synapse/storage/schema/main/delta/83/05_cross_signing_key_update_grant.sql +34 -0
  925. synapse/storage/schema/main/delta/83/06_event_push_summary_room.sql +36 -0
  926. synapse/storage/schema/main/delta/84/01_auth_links_stats.sql.postgres +20 -0
  927. synapse/storage/schema/main/delta/84/02_auth_links_index.sql +16 -0
  928. synapse/storage/schema/main/delta/84/03_auth_links_analyze.sql.postgres +16 -0
  929. synapse/storage/schema/main/delta/84/04_access_token_index.sql +15 -0
  930. synapse/storage/schema/main/delta/85/01_add_suspended.sql +14 -0
  931. synapse/storage/schema/main/delta/85/02_add_instance_names.sql +27 -0
  932. synapse/storage/schema/main/delta/85/03_new_sequences.sql.postgres +54 -0
  933. synapse/storage/schema/main/delta/85/04_cleanup_device_federation_outbox.sql +15 -0
  934. synapse/storage/schema/main/delta/85/05_add_instance_names_converted_pos.sql +16 -0
  935. synapse/storage/schema/main/delta/85/06_add_room_reports.sql +20 -0
  936. synapse/storage/schema/main/delta/86/01_authenticate_media.sql +15 -0
  937. synapse/storage/schema/main/delta/86/02_receipts_event_id_index.sql +15 -0
  938. synapse/storage/schema/main/delta/87/01_sliding_sync_memberships.sql +169 -0
  939. synapse/storage/schema/main/delta/87/02_per_connection_state.sql +81 -0
  940. synapse/storage/schema/main/delta/87/03_current_state_index.sql +19 -0
  941. synapse/storage/schema/main/delta/88/01_add_delayed_events.sql +43 -0
  942. synapse/storage/schema/main/delta/88/01_custom_profile_fields.sql +15 -0
  943. synapse/storage/schema/main/delta/88/02_fix_sliding_sync_membership_snapshots_forgotten_column.sql +21 -0
  944. synapse/storage/schema/main/delta/88/03_add_otk_ts_added_index.sql +18 -0
  945. synapse/storage/schema/main/delta/88/04_current_state_delta_index.sql +18 -0
  946. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.postgres +19 -0
  947. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.sqlite +19 -0
  948. synapse/storage/schema/main/delta/88/05_sliding_sync_room_config_index.sql +20 -0
  949. synapse/storage/schema/main/delta/88/06_events_received_ts_index.sql +17 -0
  950. synapse/storage/schema/main/delta/89/01_sliding_sync_membership_snapshot_index.sql +15 -0
  951. synapse/storage/schema/main/delta/90/01_add_column_participant_room_memberships_table.sql +16 -0
  952. synapse/storage/schema/main/delta/91/01_media_hash.sql +28 -0
  953. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.postgres +16 -0
  954. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.sqlite +16 -0
  955. synapse/storage/schema/main/delta/92/02_remove_populate_participant_bg_update.sql +17 -0
  956. synapse/storage/schema/main/delta/92/04_ss_membership_snapshot_idx.sql +16 -0
  957. synapse/storage/schema/main/delta/92/04_thread_subscriptions.sql +59 -0
  958. synapse/storage/schema/main/delta/92/04_thread_subscriptions_seq.sql.postgres +19 -0
  959. synapse/storage/schema/main/delta/92/05_fixup_max_depth_cap.sql +17 -0
  960. synapse/storage/schema/main/delta/92/05_thread_subscriptions_comments.sql.postgres +18 -0
  961. synapse/storage/schema/main/delta/92/06_device_federation_inbox_index.sql +16 -0
  962. synapse/storage/schema/main/delta/92/06_threads_last_sent_stream_ordering_comments.sql.postgres +24 -0
  963. synapse/storage/schema/main/delta/92/07_add_user_reports.sql +22 -0
  964. synapse/storage/schema/main/delta/92/07_event_txn_id_device_id_txn_id2.sql +15 -0
  965. synapse/storage/schema/main/delta/92/08_room_ban_redactions.sql +21 -0
  966. synapse/storage/schema/main/delta/92/08_thread_subscriptions_seq_fixup.sql.postgres +19 -0
  967. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql +20 -0
  968. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql.postgres +18 -0
  969. synapse/storage/schema/main/full_schemas/72/full.sql.postgres +1344 -0
  970. synapse/storage/schema/main/full_schemas/72/full.sql.sqlite +646 -0
  971. synapse/storage/schema/state/delta/23/drop_state_index.sql +35 -0
  972. synapse/storage/schema/state/delta/32/remove_state_indices.sql +38 -0
  973. synapse/storage/schema/state/delta/35/add_state_index.sql +36 -0
  974. synapse/storage/schema/state/delta/35/state.sql +41 -0
  975. synapse/storage/schema/state/delta/35/state_dedupe.sql +36 -0
  976. synapse/storage/schema/state/delta/47/state_group_seq.py +38 -0
  977. synapse/storage/schema/state/delta/56/state_group_room_idx.sql +36 -0
  978. synapse/storage/schema/state/delta/61/02state_groups_state_n_distinct.sql.postgres +34 -0
  979. synapse/storage/schema/state/delta/70/08_state_group_edges_unique.sql +36 -0
  980. synapse/storage/schema/state/delta/89/01_state_groups_deletion.sql +39 -0
  981. synapse/storage/schema/state/delta/90/02_delete_unreferenced_state_groups.sql +16 -0
  982. synapse/storage/schema/state/delta/90/03_remove_old_deletion_bg_update.sql +15 -0
  983. synapse/storage/schema/state/full_schemas/72/full.sql.postgres +30 -0
  984. synapse/storage/schema/state/full_schemas/72/full.sql.sqlite +20 -0
  985. synapse/storage/types.py +185 -0
  986. synapse/storage/util/__init__.py +20 -0
  987. synapse/storage/util/id_generators.py +909 -0
  988. synapse/storage/util/partial_state_events_tracker.py +194 -0
  989. synapse/storage/util/sequence.py +315 -0
  990. synapse/streams/__init__.py +43 -0
  991. synapse/streams/config.py +92 -0
  992. synapse/streams/events.py +203 -0
  993. synapse/synapse_rust/__init__.pyi +3 -0
  994. synapse/synapse_rust/acl.pyi +20 -0
  995. synapse/synapse_rust/events.pyi +136 -0
  996. synapse/synapse_rust/http_client.pyi +32 -0
  997. synapse/synapse_rust/push.pyi +86 -0
  998. synapse/synapse_rust/rendezvous.pyi +30 -0
  999. synapse/synapse_rust/segmenter.pyi +1 -0
  1000. synapse/synapse_rust.abi3.so +0 -0
  1001. synapse/types/__init__.py +1600 -0
  1002. synapse/types/handlers/__init__.py +93 -0
  1003. synapse/types/handlers/policy_server.py +16 -0
  1004. synapse/types/handlers/sliding_sync.py +909 -0
  1005. synapse/types/rest/__init__.py +25 -0
  1006. synapse/types/rest/client/__init__.py +415 -0
  1007. synapse/types/state.py +635 -0
  1008. synapse/types/storage/__init__.py +66 -0
  1009. synapse/util/__init__.py +170 -0
  1010. synapse/util/async_helpers.py +1067 -0
  1011. synapse/util/batching_queue.py +202 -0
  1012. synapse/util/caches/__init__.py +300 -0
  1013. synapse/util/caches/cached_call.py +143 -0
  1014. synapse/util/caches/deferred_cache.py +530 -0
  1015. synapse/util/caches/descriptors.py +694 -0
  1016. synapse/util/caches/dictionary_cache.py +350 -0
  1017. synapse/util/caches/expiringcache.py +251 -0
  1018. synapse/util/caches/lrucache.py +977 -0
  1019. synapse/util/caches/response_cache.py +323 -0
  1020. synapse/util/caches/stream_change_cache.py +370 -0
  1021. synapse/util/caches/treecache.py +189 -0
  1022. synapse/util/caches/ttlcache.py +197 -0
  1023. synapse/util/cancellation.py +63 -0
  1024. synapse/util/check_dependencies.py +335 -0
  1025. synapse/util/clock.py +500 -0
  1026. synapse/util/constants.py +22 -0
  1027. synapse/util/daemonize.py +165 -0
  1028. synapse/util/distributor.py +159 -0
  1029. synapse/util/events.py +134 -0
  1030. synapse/util/file_consumer.py +164 -0
  1031. synapse/util/frozenutils.py +57 -0
  1032. synapse/util/gai_resolver.py +180 -0
  1033. synapse/util/hash.py +38 -0
  1034. synapse/util/httpresourcetree.py +108 -0
  1035. synapse/util/iterutils.py +189 -0
  1036. synapse/util/json.py +56 -0
  1037. synapse/util/linked_list.py +156 -0
  1038. synapse/util/logcontext.py +46 -0
  1039. synapse/util/logformatter.py +28 -0
  1040. synapse/util/macaroons.py +325 -0
  1041. synapse/util/manhole.py +191 -0
  1042. synapse/util/metrics.py +340 -0
  1043. synapse/util/module_loader.py +116 -0
  1044. synapse/util/msisdn.py +51 -0
  1045. synapse/util/patch_inline_callbacks.py +250 -0
  1046. synapse/util/pydantic_models.py +56 -0
  1047. synapse/util/ratelimitutils.py +420 -0
  1048. synapse/util/retryutils.py +339 -0
  1049. synapse/util/rlimit.py +42 -0
  1050. synapse/util/rust.py +134 -0
  1051. synapse/util/sentinel.py +21 -0
  1052. synapse/util/stringutils.py +293 -0
  1053. synapse/util/task_scheduler.py +493 -0
  1054. synapse/util/templates.py +126 -0
  1055. synapse/util/threepids.py +123 -0
  1056. synapse/util/wheel_timer.py +112 -0
  1057. synapse/visibility.py +836 -0
@@ -0,0 +1,2043 @@
1
+ #
2
+ # This file is licensed under the Affero General Public License (AGPL) version 3.
3
+ #
4
+ # Copyright 2020 Sorunome
5
+ # Copyright 2014-2022 The Matrix.org Foundation C.I.C.
6
+ # Copyright (C) 2023 New Vector, Ltd
7
+ #
8
+ # This program is free software: you can redistribute it and/or modify
9
+ # it under the terms of the GNU Affero General Public License as
10
+ # published by the Free Software Foundation, either version 3 of the
11
+ # License, or (at your option) any later version.
12
+ #
13
+ # See the GNU Affero General Public License for more details:
14
+ # <https://www.gnu.org/licenses/agpl-3.0.html>.
15
+ #
16
+ # Originally licensed under the Apache License, Version 2.0:
17
+ # <http://www.apache.org/licenses/LICENSE-2.0>.
18
+ #
19
+ # [This file includes modifications made by New Vector Limited]
20
+ #
21
+ #
22
+
23
+ """Contains handlers for federation events."""
24
+
25
+ import enum
26
+ import itertools
27
+ import logging
28
+ from enum import Enum
29
+ from http import HTTPStatus
30
+ from typing import (
31
+ TYPE_CHECKING,
32
+ AbstractSet,
33
+ Iterable,
34
+ Optional,
35
+ Union,
36
+ )
37
+
38
+ import attr
39
+ from prometheus_client import Histogram
40
+ from signedjson.key import decode_verify_key_bytes
41
+ from signedjson.sign import verify_signed_json
42
+ from unpaddedbase64 import decode_base64
43
+
44
+ from synapse import event_auth
45
+ from synapse.api.constants import MAX_DEPTH, EventContentFields, EventTypes, Membership
46
+ from synapse.api.errors import (
47
+ AuthError,
48
+ CodeMessageException,
49
+ Codes,
50
+ FederationDeniedError,
51
+ FederationError,
52
+ FederationPullAttemptBackoffError,
53
+ HttpResponseException,
54
+ NotFoundError,
55
+ PartialStateConflictError,
56
+ RequestSendFailed,
57
+ SynapseError,
58
+ )
59
+ from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
60
+ from synapse.crypto.event_signing import compute_event_signature
61
+ from synapse.event_auth import validate_event_for_room_version
62
+ from synapse.events import EventBase
63
+ from synapse.events.snapshot import EventContext, UnpersistedEventContextBase
64
+ from synapse.events.validator import EventValidator
65
+ from synapse.federation.federation_client import InvalidResponseError
66
+ from synapse.handlers.pagination import PURGE_PAGINATION_LOCK_NAME
67
+ from synapse.http.servlet import assert_params_in_dict
68
+ from synapse.logging.context import nested_logging_context
69
+ from synapse.logging.opentracing import SynapseTags, set_tag, tag_args, trace
70
+ from synapse.metrics import SERVER_NAME_LABEL
71
+ from synapse.module_api import NOT_SPAM
72
+ from synapse.storage.databases.main.events_worker import EventRedactBehaviour
73
+ from synapse.storage.invite_rule import InviteRule
74
+ from synapse.types import JsonDict, StrCollection, get_domain_from_id
75
+ from synapse.types.state import StateFilter
76
+ from synapse.util.async_helpers import Linearizer
77
+ from synapse.util.retryutils import NotRetryingDestination
78
+ from synapse.visibility import filter_events_for_server
79
+
80
+ if TYPE_CHECKING:
81
+ from synapse.server import HomeServer
82
+
83
+ logger = logging.getLogger(__name__)
84
+
85
+ # Added to debug performance and track progress on optimizations
86
+ backfill_processing_before_timer = Histogram(
87
+ "synapse_federation_backfill_processing_before_time_seconds",
88
+ "sec",
89
+ labelnames=[SERVER_NAME_LABEL],
90
+ buckets=(
91
+ 0.1,
92
+ 0.5,
93
+ 1.0,
94
+ 2.5,
95
+ 5.0,
96
+ 7.5,
97
+ 10.0,
98
+ 15.0,
99
+ 20.0,
100
+ 30.0,
101
+ 40.0,
102
+ 60.0,
103
+ 80.0,
104
+ "+Inf",
105
+ ),
106
+ )
107
+
108
+
109
+ # TODO: We can refactor this away now that there is only one backfill point again
110
+ class _BackfillPointType(Enum):
111
+ # a regular backwards extremity (ie, an event which we don't yet have, but which
112
+ # is referred to by other events in the DAG)
113
+ BACKWARDS_EXTREMITY = enum.auto()
114
+
115
+
116
+ @attr.s(slots=True, auto_attribs=True, frozen=True)
117
+ class _BackfillPoint:
118
+ """A potential point we might backfill from"""
119
+
120
+ event_id: str
121
+ depth: int
122
+ type: _BackfillPointType
123
+
124
+
125
+ class FederationHandler:
126
+ """Handles general incoming federation requests
127
+
128
+ Incoming events are *not* handled here, for which see FederationEventHandler.
129
+ """
130
+
131
+ def __init__(self, hs: "HomeServer"):
132
+ self.hs = hs
133
+
134
+ self.clock = hs.get_clock()
135
+ self.store = hs.get_datastores().main
136
+ self._storage_controllers = hs.get_storage_controllers()
137
+ self._state_storage_controller = self._storage_controllers.state
138
+ self.federation_client = hs.get_federation_client()
139
+ self.state_handler = hs.get_state_handler()
140
+ self.server_name = hs.hostname
141
+ self.keyring = hs.get_keyring()
142
+ self.is_mine_id = hs.is_mine_id
143
+ self.is_mine_server_name = hs.is_mine_server_name
144
+ self._spam_checker_module_callbacks = hs.get_module_api_callbacks().spam_checker
145
+ self.event_creation_handler = hs.get_event_creation_handler()
146
+ self.event_builder_factory = hs.get_event_builder_factory()
147
+ self._event_auth_handler = hs.get_event_auth_handler()
148
+ self._server_notices_mxid = hs.config.servernotices.server_notices_mxid
149
+ self.config = hs.config
150
+ self.http_client = hs.get_proxied_blocklisted_http_client()
151
+ self._replication = hs.get_replication_data_handler()
152
+ self._federation_event_handler = hs.get_federation_event_handler()
153
+ self._device_handler = hs.get_device_handler()
154
+ self._bulk_push_rule_evaluator = hs.get_bulk_push_rule_evaluator()
155
+ self._notifier = hs.get_notifier()
156
+ self._worker_locks = hs.get_worker_locks_handler()
157
+
158
+ self._room_backfill = Linearizer(name="room_backfill", clock=self.clock)
159
+
160
+ self._third_party_event_rules = (
161
+ hs.get_module_api_callbacks().third_party_event_rules
162
+ )
163
+
164
+ # Tracks running partial state syncs by room ID.
165
+ # Partial state syncs currently only run on the main process, so it's okay to
166
+ # track them in-memory for now.
167
+ self._active_partial_state_syncs: set[str] = set()
168
+ # Tracks partial state syncs we may want to restart.
169
+ # A dictionary mapping room IDs to (initial destination, other destinations)
170
+ # tuples.
171
+ self._partial_state_syncs_maybe_needing_restart: dict[
172
+ str, tuple[Optional[str], AbstractSet[str]]
173
+ ] = {}
174
+ # A lock guarding the partial state flag for rooms.
175
+ # When the lock is held for a given room, no other concurrent code may
176
+ # partial state or un-partial state the room.
177
+ self._is_partial_state_room_linearizer = Linearizer(
178
+ name="_is_partial_state_room_linearizer",
179
+ clock=self.clock,
180
+ )
181
+
182
+ # if this is the main process, fire off a background process to resume
183
+ # any partial-state-resync operations which were in flight when we
184
+ # were shut down.
185
+ if not hs.config.worker.worker_app:
186
+ self.hs.run_as_background_process(
187
+ "resume_sync_partial_state_room",
188
+ self._resume_partial_state_room_sync,
189
+ )
190
+
191
+ @trace
192
+ @tag_args
193
+ async def maybe_backfill(
194
+ self, room_id: str, current_depth: int, limit: int, record_time: bool = True
195
+ ) -> bool:
196
+ """Checks the database to see if we should backfill before paginating,
197
+ and if so do.
198
+
199
+ Args:
200
+ room_id
201
+ current_depth: The depth from which we're paginating from. This is
202
+ used to decide if we should backfill and what extremities to
203
+ use.
204
+ limit: The number of events that the pagination request will
205
+ return. This is used as part of the heuristic to decide if we
206
+ should back paginate.
207
+ record_time: Whether to record the time it takes to backfill.
208
+
209
+ Returns:
210
+ True if we actually tried to backfill something, otherwise False.
211
+ """
212
+ # Starting the processing time here so we can include the room backfill
213
+ # linearizer lock queue in the timing
214
+ processing_start_time = self.clock.time_msec() if record_time else 0
215
+
216
+ async with self._room_backfill.queue(room_id):
217
+ async with self._worker_locks.acquire_read_write_lock(
218
+ PURGE_PAGINATION_LOCK_NAME, room_id, write=False
219
+ ):
220
+ return await self._maybe_backfill_inner(
221
+ room_id,
222
+ current_depth,
223
+ limit,
224
+ processing_start_time=processing_start_time,
225
+ )
226
+
227
+ @trace
228
+ @tag_args
229
+ async def _maybe_backfill_inner(
230
+ self,
231
+ room_id: str,
232
+ current_depth: int,
233
+ limit: int,
234
+ *,
235
+ processing_start_time: Optional[int],
236
+ ) -> bool:
237
+ """
238
+ Checks whether the `current_depth` is at or approaching any backfill
239
+ points in the room and if so, will backfill. We only care about
240
+ checking backfill points that happened before the `current_depth`
241
+ (meaning less than or equal to the `current_depth`).
242
+
243
+ Args:
244
+ room_id: The room to backfill in.
245
+ current_depth: The depth to check at for any upcoming backfill points.
246
+ limit: The max number of events to request from the remote federated server.
247
+ processing_start_time: The time when `maybe_backfill` started processing.
248
+ Only used for timing. If `None`, no timing observation will be made.
249
+
250
+ Returns:
251
+ True if we actually tried to backfill something, otherwise False.
252
+ """
253
+ backwards_extremities = [
254
+ _BackfillPoint(event_id, depth, _BackfillPointType.BACKWARDS_EXTREMITY)
255
+ for event_id, depth in await self.store.get_backfill_points_in_room(
256
+ room_id=room_id,
257
+ current_depth=current_depth,
258
+ # We only need to end up with 5 extremities combined with the
259
+ # insertion event extremities to make the `/backfill` request
260
+ # but fetch an order of magnitude more to make sure there is
261
+ # enough even after we filter them by whether visible in the
262
+ # history. This isn't fool-proof as all backfill points within
263
+ # our limit could be filtered out but seems like a good amount
264
+ # to try with at least.
265
+ limit=50,
266
+ )
267
+ ]
268
+
269
+ # we now have a list of potential places to backpaginate from. We prefer to
270
+ # start with the most recent (ie, max depth), so let's sort the list.
271
+ sorted_backfill_points: list[_BackfillPoint] = sorted(
272
+ backwards_extremities,
273
+ key=lambda e: -int(e.depth),
274
+ )
275
+
276
+ logger.debug(
277
+ "_maybe_backfill_inner: room_id: %s: current_depth: %s, limit: %s, "
278
+ "backfill points (%d): %s",
279
+ room_id,
280
+ current_depth,
281
+ limit,
282
+ len(sorted_backfill_points),
283
+ sorted_backfill_points,
284
+ )
285
+ set_tag(
286
+ SynapseTags.RESULT_PREFIX + "sorted_backfill_points",
287
+ str(sorted_backfill_points),
288
+ )
289
+ set_tag(
290
+ SynapseTags.RESULT_PREFIX + "sorted_backfill_points.length",
291
+ str(len(sorted_backfill_points)),
292
+ )
293
+
294
+ # If we have no backfill points lower than the `current_depth` then either we
295
+ # can a) bail or b) still attempt to backfill. We opt to try backfilling anyway
296
+ # just in case we do get relevant events. This is good for eventual consistency
297
+ # sake but we don't need to block the client for something that is just as
298
+ # likely not to return anything relevant so we backfill in the background. The
299
+ # only way, this could return something relevant is if we discover a new branch
300
+ # of history that extends all the way back to where we are currently paginating
301
+ # and it's within the 100 events that are returned from `/backfill`.
302
+ if not sorted_backfill_points and current_depth != MAX_DEPTH:
303
+ # Check that we actually have later backfill points, if not just return.
304
+ have_later_backfill_points = await self.store.get_backfill_points_in_room(
305
+ room_id=room_id,
306
+ current_depth=MAX_DEPTH,
307
+ limit=1,
308
+ )
309
+ if not have_later_backfill_points:
310
+ return False
311
+
312
+ logger.debug(
313
+ "_maybe_backfill_inner: all backfill points are *after* current depth. Trying again with later backfill points."
314
+ )
315
+ self.hs.run_as_background_process(
316
+ "_maybe_backfill_inner_anyway_with_max_depth",
317
+ self.maybe_backfill,
318
+ room_id=room_id,
319
+ # We use `MAX_DEPTH` so that we find all backfill points next
320
+ # time (all events are below the `MAX_DEPTH`)
321
+ current_depth=MAX_DEPTH,
322
+ limit=limit,
323
+ # We don't want to start another timing observation from this
324
+ # nested recursive call. The top-most call can record the time
325
+ # overall otherwise the smaller one will throw off the results.
326
+ record_time=False,
327
+ )
328
+ # We return `False` because we're backfilling in the background and there is
329
+ # no new events immediately for the caller to know about yet.
330
+ return False
331
+
332
+ # Even after recursing with `MAX_DEPTH`, we didn't find any
333
+ # backward extremities to backfill from.
334
+ if not sorted_backfill_points:
335
+ logger.debug(
336
+ "_maybe_backfill_inner: Not backfilling as no backward extremeties found."
337
+ )
338
+ return False
339
+
340
+ # If we're approaching an extremity we trigger a backfill, otherwise we
341
+ # no-op.
342
+ #
343
+ # We chose twice the limit here as then clients paginating backwards
344
+ # will send pagination requests that trigger backfill at least twice
345
+ # using the most recent extremity before it gets removed (see below). We
346
+ # chose more than one times the limit in case of failure, but choosing a
347
+ # much larger factor will result in triggering a backfill request much
348
+ # earlier than necessary.
349
+ max_depth_of_backfill_points = sorted_backfill_points[0].depth
350
+ if current_depth - 2 * limit > max_depth_of_backfill_points:
351
+ logger.debug(
352
+ "Not backfilling as we don't need to. %d < %d - 2 * %d",
353
+ max_depth_of_backfill_points,
354
+ current_depth,
355
+ limit,
356
+ )
357
+ return False
358
+
359
+ # For performance's sake, we only want to paginate from a particular extremity
360
+ # if we can actually see the events we'll get. Otherwise, we'd just spend a lot
361
+ # of resources to get redacted events. We check each extremity in turn and
362
+ # ignore those which users on our server wouldn't be able to see.
363
+ #
364
+ # Additionally, we limit ourselves to backfilling from at most 5 extremities,
365
+ # for two reasons:
366
+ #
367
+ # - The check which determines if we can see an extremity's events can be
368
+ # expensive (we load the full state for the room at each of the backfill
369
+ # points, or (worse) their successors)
370
+ # - We want to avoid the server-server API request URI becoming too long.
371
+ #
372
+ # *Note*: the spec wants us to keep backfilling until we reach the start
373
+ # of the room in case we are allowed to see some of the history. However,
374
+ # in practice that causes more issues than its worth, as (a) it's
375
+ # relatively rare for there to be any visible history and (b) even when
376
+ # there is it's often sufficiently long ago that clients would stop
377
+ # attempting to paginate before backfill reached the visible history.
378
+
379
+ extremities_to_request: list[str] = []
380
+ for bp in sorted_backfill_points:
381
+ if len(extremities_to_request) >= 5:
382
+ break
383
+
384
+ # For regular backwards extremities, we don't have the extremity events
385
+ # themselves, so we need to actually check the events that reference them -
386
+ # their "successor" events.
387
+ #
388
+ # TODO: Correctly handle the case where we are allowed to see the
389
+ # successor event but not the backward extremity, e.g. in the case of
390
+ # initial join of the server where we are allowed to see the join
391
+ # event but not anything before it. This would require looking at the
392
+ # state *before* the event, ignoring the special casing certain event
393
+ # types have.
394
+ event_ids_to_check = await self.store.get_successor_events(bp.event_id)
395
+
396
+ events_to_check = await self.store.get_events_as_list(
397
+ event_ids_to_check,
398
+ redact_behaviour=EventRedactBehaviour.as_is,
399
+ get_prev_content=False,
400
+ )
401
+
402
+ # We unset `filter_out_erased_senders` as we might otherwise get false
403
+ # positives from users having been erased.
404
+ filtered_extremities = await filter_events_for_server(
405
+ self._storage_controllers,
406
+ self.server_name,
407
+ self.server_name,
408
+ events_to_check,
409
+ redact=False,
410
+ filter_out_erased_senders=False,
411
+ filter_out_remote_partial_state_events=False,
412
+ )
413
+ if filtered_extremities:
414
+ extremities_to_request.append(bp.event_id)
415
+ else:
416
+ logger.debug(
417
+ "_maybe_backfill_inner: skipping extremity %s as it would not be visible",
418
+ bp,
419
+ )
420
+
421
+ if not extremities_to_request:
422
+ logger.debug(
423
+ "_maybe_backfill_inner: found no extremities which would be visible"
424
+ )
425
+ return False
426
+
427
+ logger.debug(
428
+ "_maybe_backfill_inner: extremities_to_request %s", extremities_to_request
429
+ )
430
+ set_tag(
431
+ SynapseTags.RESULT_PREFIX + "extremities_to_request",
432
+ str(extremities_to_request),
433
+ )
434
+ set_tag(
435
+ SynapseTags.RESULT_PREFIX + "extremities_to_request.length",
436
+ str(len(extremities_to_request)),
437
+ )
438
+
439
+ # Now we need to decide which hosts to hit first.
440
+ # First we try hosts that are already in the room.
441
+ # TODO: HEURISTIC ALERT.
442
+ likely_domains = (
443
+ await self._storage_controllers.state.get_current_hosts_in_room_ordered(
444
+ room_id
445
+ )
446
+ )
447
+
448
+ async def try_backfill(domains: StrCollection) -> bool:
449
+ # TODO: Should we try multiple of these at a time?
450
+
451
+ # Number of contacted remote homeservers that have denied our backfill
452
+ # request with a 4xx code.
453
+ denied_count = 0
454
+
455
+ # Maximum number of contacted remote homeservers that can deny our
456
+ # backfill request with 4xx codes before we give up.
457
+ max_denied_count = 5
458
+
459
+ for dom in domains:
460
+ # We don't want to ask our own server for information we don't have
461
+ if self.is_mine_server_name(dom):
462
+ continue
463
+
464
+ try:
465
+ await self._federation_event_handler.backfill(
466
+ dom, room_id, limit=100, extremities=extremities_to_request
467
+ )
468
+ # If this succeeded then we probably already have the
469
+ # appropriate stuff.
470
+ # TODO: We can probably do something more intelligent here.
471
+ return True
472
+ except NotRetryingDestination as e:
473
+ logger.info("_maybe_backfill_inner: %s", e)
474
+ continue
475
+ except FederationDeniedError:
476
+ logger.info(
477
+ "_maybe_backfill_inner: Not attempting to backfill from %s because the homeserver is not on our federation whitelist",
478
+ dom,
479
+ )
480
+ continue
481
+ except (SynapseError, InvalidResponseError) as e:
482
+ logger.info("Failed to backfill from %s because %s", dom, e)
483
+ continue
484
+ except HttpResponseException as e:
485
+ if 400 <= e.code < 500:
486
+ logger.warning(
487
+ "Backfill denied from %s because %s [%d/%d]",
488
+ dom,
489
+ e,
490
+ denied_count,
491
+ max_denied_count,
492
+ )
493
+ denied_count += 1
494
+ if denied_count >= max_denied_count:
495
+ return False
496
+ continue
497
+
498
+ logger.info("Failed to backfill from %s because %s", dom, e)
499
+ continue
500
+ except CodeMessageException as e:
501
+ if 400 <= e.code < 500:
502
+ logger.warning(
503
+ "Backfill denied from %s because %s [%d/%d]",
504
+ dom,
505
+ e,
506
+ denied_count,
507
+ max_denied_count,
508
+ )
509
+ denied_count += 1
510
+ if denied_count >= max_denied_count:
511
+ return False
512
+ continue
513
+
514
+ logger.info("Failed to backfill from %s because %s", dom, e)
515
+ continue
516
+ except RequestSendFailed as e:
517
+ logger.info("Failed to get backfill from %s because %s", dom, e)
518
+ continue
519
+ except Exception as e:
520
+ logger.exception("Failed to backfill from %s because %s", dom, e)
521
+ continue
522
+
523
+ return False
524
+
525
+ # If we have the `processing_start_time`, then we can make an
526
+ # observation. We wouldn't have the `processing_start_time` in the case
527
+ # where `_maybe_backfill_inner` is recursively called to find any
528
+ # backfill points regardless of `current_depth`.
529
+ if processing_start_time is not None:
530
+ processing_end_time = self.clock.time_msec()
531
+ backfill_processing_before_timer.labels(
532
+ **{SERVER_NAME_LABEL: self.server_name}
533
+ ).observe((processing_end_time - processing_start_time) / 1000)
534
+
535
+ success = await try_backfill(likely_domains)
536
+ if success:
537
+ return True
538
+
539
+ # TODO: we could also try servers which were previously in the room, but
540
+ # are no longer.
541
+
542
+ return False
543
+
544
+ async def send_invite(self, target_host: str, event: EventBase) -> EventBase:
545
+ """Sends the invite to the remote server for signing.
546
+
547
+ Invites must be signed by the invitee's server before distribution.
548
+ """
549
+ try:
550
+ pdu = await self.federation_client.send_invite(
551
+ destination=target_host,
552
+ room_id=event.room_id,
553
+ event_id=event.event_id,
554
+ pdu=event,
555
+ )
556
+ except RequestSendFailed:
557
+ raise SynapseError(502, f"Can't connect to server {target_host}")
558
+
559
+ return pdu
560
+
561
+ async def on_event_auth(self, event_id: str) -> list[EventBase]:
562
+ event = await self.store.get_event(event_id)
563
+ auth = await self.store.get_auth_chain(
564
+ event.room_id, list(event.auth_event_ids()), include_given=True
565
+ )
566
+ return list(auth)
567
+
568
+ async def do_invite_join(
569
+ self, target_hosts: Iterable[str], room_id: str, joinee: str, content: JsonDict
570
+ ) -> tuple[str, int]:
571
+ """Attempts to join the `joinee` to the room `room_id` via the
572
+ servers contained in `target_hosts`.
573
+
574
+ This first triggers a /make_join/ request that returns a partial
575
+ event that we can fill out and sign. This is then sent to the
576
+ remote server via /send_join/ which responds with the state at that
577
+ event and the auth_chains.
578
+
579
+ We suspend processing of any received events from this room until we
580
+ have finished processing the join.
581
+
582
+ Args:
583
+ target_hosts: List of servers to attempt to join the room with.
584
+
585
+ room_id: The ID of the room to join.
586
+
587
+ joinee: The User ID of the joining user.
588
+
589
+ content: The event content to use for the join event.
590
+ """
591
+ # TODO: We should be able to call this on workers, but the upgrading of
592
+ # room stuff after join currently doesn't work on workers.
593
+ # TODO: Before we relax this condition, we need to allow re-syncing of
594
+ # partial room state to happen on workers.
595
+ assert self.config.worker.worker_app is None
596
+
597
+ logger.debug("Joining %s to %s", joinee, room_id)
598
+
599
+ origin, event, room_version_obj = await self._make_and_verify_event(
600
+ target_hosts,
601
+ room_id,
602
+ joinee,
603
+ "join",
604
+ content,
605
+ params={"ver": KNOWN_ROOM_VERSIONS},
606
+ )
607
+
608
+ # This shouldn't happen, because the RoomMemberHandler has a
609
+ # linearizer lock which only allows one operation per user per room
610
+ # at a time - so this is just paranoia.
611
+ assert room_id not in self._federation_event_handler.room_queues
612
+
613
+ self._federation_event_handler.room_queues[room_id] = []
614
+
615
+ is_host_joined = await self.store.is_host_joined(room_id, self.server_name)
616
+
617
+ if not is_host_joined:
618
+ # We may have old forward extremities lying around if the homeserver left
619
+ # the room completely in the past. Clear them out.
620
+ #
621
+ # Note that this check-then-clear is subject to races where
622
+ # * the homeserver is in the room and stops being in the room just after
623
+ # the check. We won't reset the forward extremities, but that's okay,
624
+ # since they will be almost up to date.
625
+ # * the homeserver is not in the room and starts being in the room just
626
+ # after the check. This can't happen, since `RoomMemberHandler` has a
627
+ # linearizer lock which prevents concurrent remote joins into the same
628
+ # room.
629
+ # In short, the races either have an acceptable outcome or should be
630
+ # impossible.
631
+ await self.store.clean_room_for_join(room_id)
632
+
633
+ try:
634
+ # Try the host we successfully got a response to /make_join/
635
+ # request first.
636
+ host_list = list(target_hosts)
637
+ try:
638
+ host_list.remove(origin)
639
+ host_list.insert(0, origin)
640
+ except ValueError:
641
+ pass
642
+
643
+ async with self._is_partial_state_room_linearizer.queue(room_id):
644
+ already_partial_state_room = await self.store.is_partial_state_room(
645
+ room_id
646
+ )
647
+
648
+ ret = await self.federation_client.send_join(
649
+ host_list,
650
+ event,
651
+ room_version_obj,
652
+ # Perform a full join when we are already in the room and it is a
653
+ # full state room, since we are not allowed to persist a partial
654
+ # state join event in a full state room. In the future, we could
655
+ # optimize this by always performing a partial state join and
656
+ # computing the state ourselves or retrieving it from the remote
657
+ # homeserver if necessary.
658
+ #
659
+ # There's a race where we leave the room, then perform a full join
660
+ # anyway. This should end up being fast anyway, since we would
661
+ # already have the full room state and auth chain persisted.
662
+ partial_state=not is_host_joined or already_partial_state_room,
663
+ )
664
+
665
+ event = ret.event
666
+ origin = ret.origin
667
+ state = ret.state
668
+ auth_chain = ret.auth_chain
669
+ auth_chain.sort(key=lambda e: e.depth)
670
+
671
+ logger.debug("do_invite_join auth_chain: %s", auth_chain)
672
+ logger.debug("do_invite_join state: %s", state)
673
+
674
+ logger.debug("do_invite_join event: %s", event)
675
+
676
+ # if this is the first time we've joined this room, it's time to add
677
+ # a row to `rooms` with the correct room version. If there's already a
678
+ # row there, we should override it, since it may have been populated
679
+ # based on an invite request which lied about the room version.
680
+ #
681
+ # federation_client.send_join has already checked that the room
682
+ # version in the received create event is the same as room_version_obj,
683
+ # so we can rely on it now.
684
+ #
685
+ await self.store.upsert_room_on_join(
686
+ room_id=room_id,
687
+ room_version=room_version_obj,
688
+ state_events=state,
689
+ )
690
+
691
+ if ret.partial_state and not already_partial_state_room:
692
+ # Mark the room as having partial state.
693
+ # The background process is responsible for unmarking this flag,
694
+ # even if the join fails.
695
+ # TODO(faster_joins):
696
+ # We may want to reset the partial state info if it's from an
697
+ # old, failed partial state join.
698
+ # https://github.com/matrix-org/synapse/issues/13000
699
+
700
+ # FIXME: Ideally, we would store the full stream token here
701
+ # not just the minimum stream ID, so that we can compute an
702
+ # accurate list of device changes when un-partial-ing the
703
+ # room. The only side effect of this is that we may send
704
+ # extra unecessary device list outbound pokes through
705
+ # federation, which is harmless.
706
+ device_lists_stream_id = self.store.get_device_stream_token().stream
707
+
708
+ await self.store.store_partial_state_room(
709
+ room_id=room_id,
710
+ servers=ret.servers_in_room,
711
+ device_lists_stream_id=device_lists_stream_id,
712
+ joined_via=origin,
713
+ )
714
+
715
+ try:
716
+ max_stream_id = (
717
+ await self._federation_event_handler.process_remote_join(
718
+ origin,
719
+ room_id,
720
+ auth_chain,
721
+ state,
722
+ event,
723
+ room_version_obj,
724
+ partial_state=ret.partial_state,
725
+ )
726
+ )
727
+ except PartialStateConflictError:
728
+ # This should be impossible, since we hold the lock on the room's
729
+ # partial statedness.
730
+ logger.error(
731
+ "Room %s was un-partial stated while processing remote join.",
732
+ room_id,
733
+ )
734
+ raise
735
+ else:
736
+ # Record the join event id for future use (when we finish the full
737
+ # join). We have to do this after persisting the event to keep
738
+ # foreign key constraints intact.
739
+ if ret.partial_state and not already_partial_state_room:
740
+ # TODO(faster_joins):
741
+ # We may want to reset the partial state info if it's from
742
+ # an old, failed partial state join.
743
+ # https://github.com/matrix-org/synapse/issues/13000
744
+ await self.store.write_partial_state_rooms_join_event_id(
745
+ room_id, event.event_id
746
+ )
747
+ finally:
748
+ # Always kick off the background process that asynchronously fetches
749
+ # state for the room.
750
+ # If the join failed, the background process is responsible for
751
+ # cleaning up — including unmarking the room as a partial state
752
+ # room.
753
+ if ret.partial_state:
754
+ # Kick off the process of asynchronously fetching the state for
755
+ # this room.
756
+ self._start_partial_state_room_sync(
757
+ initial_destination=origin,
758
+ other_destinations=ret.servers_in_room,
759
+ room_id=room_id,
760
+ )
761
+
762
+ # We wait here until this instance has seen the events come down
763
+ # replication (if we're using replication) as the below uses caches.
764
+ await self._replication.wait_for_stream_position(
765
+ self.config.worker.events_shard_config.get_instance(room_id),
766
+ "events",
767
+ max_stream_id,
768
+ )
769
+
770
+ # Check whether this room is the result of an upgrade of a room we already know
771
+ # about. If so, migrate over user information
772
+ predecessor = await self.store.get_room_predecessor(room_id)
773
+ if not predecessor or not isinstance(predecessor.get("room_id"), str):
774
+ return event.event_id, max_stream_id
775
+ old_room_id = predecessor["room_id"]
776
+ logger.debug(
777
+ "Found predecessor for %s during remote join: %s", room_id, old_room_id
778
+ )
779
+
780
+ # We retrieve the room member handler here as to not cause a cyclic dependency
781
+ member_handler = self.hs.get_room_member_handler()
782
+ await member_handler.transfer_room_state_on_room_upgrade(
783
+ old_room_id, room_id
784
+ )
785
+
786
+ logger.debug("Finished joining %s to %s", joinee, room_id)
787
+ return event.event_id, max_stream_id
788
+ finally:
789
+ room_queue = self._federation_event_handler.room_queues[room_id]
790
+ del self._federation_event_handler.room_queues[room_id]
791
+
792
+ # we don't need to wait for the queued events to be processed -
793
+ # it's just a best-effort thing at this point. We do want to do
794
+ # them roughly in order, though, otherwise we'll end up making
795
+ # lots of requests for missing prev_events which we do actually
796
+ # have. Hence we fire off the background task, but don't wait for it.
797
+
798
+ self.hs.run_as_background_process(
799
+ "handle_queued_pdus",
800
+ self._handle_queued_pdus,
801
+ room_queue,
802
+ )
803
+
804
+ async def do_knock(
805
+ self,
806
+ target_hosts: list[str],
807
+ room_id: str,
808
+ knockee: str,
809
+ content: JsonDict,
810
+ ) -> tuple[str, int]:
811
+ """Sends the knock to the remote server.
812
+
813
+ This first triggers a make_knock request that returns a partial
814
+ event that we can fill out and sign. This is then sent to the
815
+ remote server via send_knock.
816
+
817
+ Knock events must be signed by the knockee's server before distributing.
818
+
819
+ Args:
820
+ target_hosts: A list of hosts that we want to try knocking through.
821
+ room_id: The ID of the room to knock on.
822
+ knockee: The ID of the user who is knocking.
823
+ content: The content of the knock event.
824
+
825
+ Returns:
826
+ A tuple of (event ID, stream ID).
827
+
828
+ Raises:
829
+ SynapseError: If the chosen remote server returns a 3xx/4xx code.
830
+ RuntimeError: If no servers were reachable.
831
+ """
832
+ logger.debug("Knocking on room %s on behalf of user %s", room_id, knockee)
833
+
834
+ # Inform the remote server of the room versions we support
835
+ supported_room_versions = list(KNOWN_ROOM_VERSIONS.keys())
836
+
837
+ # Ask the remote server to create a valid knock event for us. Once received,
838
+ # we sign the event
839
+ params: dict[str, Iterable[str]] = {"ver": supported_room_versions}
840
+ origin, event, event_format_version = await self._make_and_verify_event(
841
+ target_hosts, room_id, knockee, Membership.KNOCK, content, params=params
842
+ )
843
+
844
+ # Mark the knock as an outlier as we don't yet have the state at this point in
845
+ # the DAG.
846
+ event.internal_metadata.outlier = True
847
+
848
+ # ... but tell /sync to send it to clients anyway.
849
+ event.internal_metadata.out_of_band_membership = True
850
+
851
+ # Record the room ID and its version so that we have a record of the room
852
+ await self.store.maybe_store_room_on_outlier_membership(
853
+ room_id=event.room_id, room_version=event_format_version
854
+ )
855
+
856
+ # Initially try the host that we successfully called /make_knock on
857
+ try:
858
+ target_hosts.remove(origin)
859
+ target_hosts.insert(0, origin)
860
+ except ValueError:
861
+ pass
862
+
863
+ # Send the signed event back to the room, and potentially receive some
864
+ # further information about the room in the form of partial state events
865
+ knock_response = await self.federation_client.send_knock(target_hosts, event)
866
+
867
+ # Store any stripped room state events in the "unsigned" key of the event.
868
+ # This is a bit of a hack and is cribbing off of invites. Basically we
869
+ # store the room state here and retrieve it again when this event appears
870
+ # in the invitee's sync stream. It is stripped out for all other local users.
871
+ stripped_room_state = knock_response.get("knock_room_state")
872
+
873
+ if stripped_room_state is None:
874
+ raise KeyError("Missing 'knock_room_state' field in send_knock response")
875
+
876
+ if not isinstance(stripped_room_state, list):
877
+ raise TypeError("'knock_room_state' has wrong type")
878
+
879
+ event.unsigned["knock_room_state"] = stripped_room_state
880
+
881
+ context = EventContext.for_outlier(self._storage_controllers)
882
+ stream_id = await self._federation_event_handler.persist_events_and_notify(
883
+ event.room_id, [(event, context)]
884
+ )
885
+ return event.event_id, stream_id
886
+
887
+ async def _handle_queued_pdus(
888
+ self, room_queue: list[tuple[EventBase, str]]
889
+ ) -> None:
890
+ """Process PDUs which got queued up while we were busy send_joining.
891
+
892
+ Args:
893
+ room_queue: list of PDUs to be processed and the servers that sent them
894
+ """
895
+ for p, origin in room_queue:
896
+ try:
897
+ logger.info(
898
+ "Processing queued PDU %s which was received while we were joining",
899
+ p,
900
+ )
901
+ with nested_logging_context(p.event_id):
902
+ await self._federation_event_handler.on_receive_pdu(origin, p)
903
+ except Exception as e:
904
+ logger.warning(
905
+ "Error handling queued PDU %s from %s: %s", p.event_id, origin, e
906
+ )
907
+
908
+ async def on_make_join_request(
909
+ self, origin: str, room_id: str, user_id: str
910
+ ) -> EventBase:
911
+ """We've received a /make_join/ request, so we create a partial
912
+ join event for the room and return that. We do *not* persist or
913
+ process it until the other server has signed it and sent it back.
914
+
915
+ Args:
916
+ origin: The (verified) server name of the requesting server.
917
+ room_id: Room to create join event in
918
+ user_id: The user to create the join for
919
+ """
920
+ if get_domain_from_id(user_id) != origin:
921
+ logger.info(
922
+ "Got /make_join request for user %r from different origin %s, ignoring",
923
+ user_id,
924
+ origin,
925
+ )
926
+ raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
927
+
928
+ # checking the room version will check that we've actually heard of the room
929
+ # (and return a 404 otherwise)
930
+ room_version = await self.store.get_room_version(room_id)
931
+
932
+ if await self.store.is_partial_state_room(room_id):
933
+ # If our server is still only partially joined, we can't give a complete
934
+ # response to /make_join, so return a 404 as we would if we weren't in the
935
+ # room at all.
936
+ # The main reason we can't respond properly is that we need to know about
937
+ # the auth events for the join event that we would return.
938
+ # We also should not bother entertaining the /make_join since we cannot
939
+ # handle the /send_join.
940
+ logger.info(
941
+ "Rejecting /make_join to %s because it's a partial state room", room_id
942
+ )
943
+ raise SynapseError(
944
+ 404,
945
+ "Unable to handle /make_join right now; this server is not fully joined.",
946
+ errcode=Codes.NOT_FOUND,
947
+ )
948
+
949
+ # now check that we are *still* in the room
950
+ is_in_room = await self._event_auth_handler.is_host_in_room(
951
+ room_id, self.server_name
952
+ )
953
+ if not is_in_room:
954
+ logger.info(
955
+ "Got /make_join request for room %s we are no longer in",
956
+ room_id,
957
+ )
958
+ raise NotFoundError("Not an active room on this server")
959
+
960
+ event_content = {"membership": Membership.JOIN}
961
+
962
+ # If the current room is using restricted join rules, additional information
963
+ # may need to be included in the event content in order to efficiently
964
+ # validate the event.
965
+ #
966
+ # Note that this requires the /send_join request to come back to the
967
+ # same server.
968
+ prev_event_ids = None
969
+ if room_version.restricted_join_rule:
970
+ # Note that the room's state can change out from under us and render our
971
+ # nice join rules-conformant event non-conformant by the time we build the
972
+ # event. When this happens, our validation at the end fails and we respond
973
+ # to the requesting server with a 403, which is misleading — it indicates
974
+ # that the user is not allowed to join the room and the joining server
975
+ # should not bother retrying via this homeserver or any others, when
976
+ # in fact we've just messed up with building the event.
977
+ #
978
+ # To reduce the likelihood of this race, we capture the forward extremities
979
+ # of the room (prev_event_ids) just before fetching the current state, and
980
+ # hope that the state we fetch corresponds to the prev events we chose.
981
+ prev_event_ids = await self.store.get_prev_events_for_room(room_id)
982
+ state_ids = await self._state_storage_controller.get_current_state_ids(
983
+ room_id
984
+ )
985
+ if await self._event_auth_handler.has_restricted_join_rules(
986
+ state_ids, room_version
987
+ ):
988
+ prev_member_event_id = state_ids.get((EventTypes.Member, user_id), None)
989
+ # If the user is invited or joined to the room already, then
990
+ # no additional info is needed.
991
+ include_auth_user_id = True
992
+ if prev_member_event_id:
993
+ prev_member_event = await self.store.get_event(prev_member_event_id)
994
+ include_auth_user_id = prev_member_event.membership not in (
995
+ Membership.JOIN,
996
+ Membership.INVITE,
997
+ )
998
+
999
+ if include_auth_user_id:
1000
+ event_content[
1001
+ EventContentFields.AUTHORISING_USER
1002
+ ] = await self._event_auth_handler.get_user_which_could_invite(
1003
+ room_id,
1004
+ state_ids,
1005
+ )
1006
+
1007
+ builder = self.event_builder_factory.for_room_version(
1008
+ room_version,
1009
+ {
1010
+ "type": EventTypes.Member,
1011
+ "content": event_content,
1012
+ "room_id": room_id,
1013
+ "sender": user_id,
1014
+ "state_key": user_id,
1015
+ },
1016
+ )
1017
+
1018
+ try:
1019
+ (
1020
+ event,
1021
+ unpersisted_context,
1022
+ ) = await self.event_creation_handler.create_new_client_event(
1023
+ builder=builder,
1024
+ prev_event_ids=prev_event_ids,
1025
+ )
1026
+ except SynapseError as e:
1027
+ logger.warning("Failed to create join to %s because %s", room_id, e)
1028
+ raise
1029
+
1030
+ # Ensure the user can even join the room.
1031
+ await self._federation_event_handler.check_join_restrictions(
1032
+ unpersisted_context, event
1033
+ )
1034
+
1035
+ # The remote hasn't signed it yet, obviously. We'll do the full checks
1036
+ # when we get the event back in `on_send_join_request`
1037
+ await self._event_auth_handler.check_auth_rules_from_context(event)
1038
+ return event
1039
+
1040
+ async def on_invite_request(
1041
+ self, origin: str, event: EventBase, room_version: RoomVersion
1042
+ ) -> EventBase:
1043
+ """We've got an invite event. Process and persist it. Sign it.
1044
+
1045
+ Respond with the now signed event.
1046
+ """
1047
+ if event.state_key is None:
1048
+ raise SynapseError(400, "The invite event did not have a state key")
1049
+
1050
+ is_blocked = await self.store.is_room_blocked(event.room_id)
1051
+ if is_blocked:
1052
+ raise SynapseError(403, "This room has been blocked on this server")
1053
+
1054
+ if self.hs.config.server.block_non_admin_invites:
1055
+ raise SynapseError(403, "This server does not accept room invites")
1056
+
1057
+ spam_check = (
1058
+ await self._spam_checker_module_callbacks.federated_user_may_invite(event)
1059
+ )
1060
+ if spam_check != NOT_SPAM:
1061
+ raise SynapseError(
1062
+ 403,
1063
+ "This user is not permitted to send invites to this server/user",
1064
+ errcode=spam_check[0],
1065
+ additional_fields=spam_check[1],
1066
+ )
1067
+
1068
+ membership = event.content.get("membership")
1069
+ if event.type != EventTypes.Member or membership != Membership.INVITE:
1070
+ raise SynapseError(400, "The event was not an m.room.member invite event")
1071
+
1072
+ sender_domain = get_domain_from_id(event.sender)
1073
+ if sender_domain != origin:
1074
+ raise SynapseError(
1075
+ 400, "The invite event was not from the server sending it"
1076
+ )
1077
+
1078
+ if not self.is_mine_id(event.state_key):
1079
+ raise SynapseError(400, "The invite event must be for this server")
1080
+
1081
+ # block any attempts to invite the server notices mxid
1082
+ if event.state_key == self._server_notices_mxid:
1083
+ raise SynapseError(HTTPStatus.FORBIDDEN, "Cannot invite this user")
1084
+
1085
+ # check the invitee's configuration and apply rules
1086
+ invite_config = await self.store.get_invite_config_for_user(event.state_key)
1087
+ rule = invite_config.get_invite_rule(event.sender)
1088
+ if rule == InviteRule.BLOCK:
1089
+ logger.info(
1090
+ "Automatically rejecting invite from %s due to the invite filtering rules of %s",
1091
+ event.sender,
1092
+ event.state_key,
1093
+ )
1094
+ raise SynapseError(
1095
+ 403,
1096
+ "You are not permitted to invite this user.",
1097
+ errcode=Codes.INVITE_BLOCKED,
1098
+ )
1099
+ # InviteRule.IGNORE is handled at the sync layer
1100
+
1101
+ # We retrieve the room member handler here as to not cause a cyclic dependency
1102
+ member_handler = self.hs.get_room_member_handler()
1103
+ # We don't rate limit based on room ID, as that should be done by
1104
+ # sending server.
1105
+ await member_handler.ratelimit_invite(None, None, event.state_key)
1106
+
1107
+ # keep a record of the room version, if we don't yet know it.
1108
+ # (this may get overwritten if we later get a different room version in a
1109
+ # join dance).
1110
+ await self.store.maybe_store_room_on_outlier_membership(
1111
+ room_id=event.room_id, room_version=room_version
1112
+ )
1113
+
1114
+ event.internal_metadata.outlier = True
1115
+ event.internal_metadata.out_of_band_membership = True
1116
+
1117
+ event.signatures.update(
1118
+ compute_event_signature(
1119
+ room_version,
1120
+ event.get_pdu_json(),
1121
+ self.hs.hostname,
1122
+ self.hs.signing_key,
1123
+ )
1124
+ )
1125
+
1126
+ context = EventContext.for_outlier(self._storage_controllers)
1127
+
1128
+ await self._bulk_push_rule_evaluator.action_for_events_by_user(
1129
+ [(event, context)]
1130
+ )
1131
+ try:
1132
+ await self._federation_event_handler.persist_events_and_notify(
1133
+ event.room_id, [(event, context)]
1134
+ )
1135
+ except Exception:
1136
+ await self.store.remove_push_actions_from_staging(event.event_id)
1137
+ raise
1138
+
1139
+ return event
1140
+
1141
+ async def do_remotely_reject_invite(
1142
+ self, target_hosts: Iterable[str], room_id: str, user_id: str, content: JsonDict
1143
+ ) -> tuple[EventBase, int]:
1144
+ origin, event, room_version = await self._make_and_verify_event(
1145
+ target_hosts, room_id, user_id, "leave", content=content
1146
+ )
1147
+ # Mark as outlier as we don't have any state for this event; we're not
1148
+ # even in the room.
1149
+ event.internal_metadata.outlier = True
1150
+ event.internal_metadata.out_of_band_membership = True
1151
+
1152
+ # Try the host that we successfully called /make_leave/ on first for
1153
+ # the /send_leave/ request.
1154
+ host_list = list(target_hosts)
1155
+ try:
1156
+ host_list.remove(origin)
1157
+ host_list.insert(0, origin)
1158
+ except ValueError:
1159
+ pass
1160
+
1161
+ await self.federation_client.send_leave(host_list, event)
1162
+
1163
+ context = EventContext.for_outlier(self._storage_controllers)
1164
+ stream_id = await self._federation_event_handler.persist_events_and_notify(
1165
+ event.room_id, [(event, context)]
1166
+ )
1167
+
1168
+ return event, stream_id
1169
+
1170
+ async def _make_and_verify_event(
1171
+ self,
1172
+ target_hosts: Iterable[str],
1173
+ room_id: str,
1174
+ user_id: str,
1175
+ membership: str,
1176
+ content: JsonDict,
1177
+ params: Optional[dict[str, Union[str, Iterable[str]]]] = None,
1178
+ ) -> tuple[str, EventBase, RoomVersion]:
1179
+ (
1180
+ origin,
1181
+ event,
1182
+ room_version,
1183
+ ) = await self.federation_client.make_membership_event(
1184
+ target_hosts, room_id, user_id, membership, content, params=params
1185
+ )
1186
+
1187
+ logger.debug("Got response to make_%s: %s", membership, event)
1188
+
1189
+ # We should assert some things.
1190
+ # FIXME: Do this in a nicer way
1191
+ assert event.type == EventTypes.Member
1192
+ assert event.user_id == user_id
1193
+ assert event.state_key == user_id
1194
+ assert event.room_id == room_id
1195
+ return origin, event, room_version
1196
+
1197
+ async def on_make_leave_request(
1198
+ self, origin: str, room_id: str, user_id: str
1199
+ ) -> EventBase:
1200
+ """We've received a /make_leave/ request, so we create a partial
1201
+ leave event for the room and return that. We do *not* persist or
1202
+ process it until the other server has signed it and sent it back.
1203
+
1204
+ Args:
1205
+ origin: The (verified) server name of the requesting server.
1206
+ room_id: Room to create leave event in
1207
+ user_id: The user to create the leave for
1208
+ """
1209
+ if get_domain_from_id(user_id) != origin:
1210
+ logger.info(
1211
+ "Got /make_leave request for user %r from different origin %s, ignoring",
1212
+ user_id,
1213
+ origin,
1214
+ )
1215
+ raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
1216
+
1217
+ room_version_obj = await self.store.get_room_version(room_id)
1218
+ builder = self.event_builder_factory.for_room_version(
1219
+ room_version_obj,
1220
+ {
1221
+ "type": EventTypes.Member,
1222
+ "content": {"membership": Membership.LEAVE},
1223
+ "room_id": room_id,
1224
+ "sender": user_id,
1225
+ "state_key": user_id,
1226
+ },
1227
+ )
1228
+
1229
+ event, _ = await self.event_creation_handler.create_new_client_event(
1230
+ builder=builder
1231
+ )
1232
+
1233
+ try:
1234
+ # The remote hasn't signed it yet, obviously. We'll do the full checks
1235
+ # when we get the event back in `on_send_leave_request`
1236
+ await self._event_auth_handler.check_auth_rules_from_context(event)
1237
+ except AuthError as e:
1238
+ logger.warning("Failed to create new leave %r because %s", event, e)
1239
+ raise e
1240
+
1241
+ return event
1242
+
1243
+ async def on_make_knock_request(
1244
+ self, origin: str, room_id: str, user_id: str
1245
+ ) -> EventBase:
1246
+ """We've received a make_knock request, so we create a partial
1247
+ knock event for the room and return that. We do *not* persist or
1248
+ process it until the other server has signed it and sent it back.
1249
+
1250
+ Args:
1251
+ origin: The (verified) server name of the requesting server.
1252
+ room_id: The room to create the knock event in.
1253
+ user_id: The user to create the knock for.
1254
+
1255
+ Returns:
1256
+ The partial knock event.
1257
+ """
1258
+ if get_domain_from_id(user_id) != origin:
1259
+ logger.info(
1260
+ "Get /make_knock request for user %r from different origin %s, ignoring",
1261
+ user_id,
1262
+ origin,
1263
+ )
1264
+ raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
1265
+
1266
+ room_version_obj = await self.store.get_room_version(room_id)
1267
+
1268
+ builder = self.event_builder_factory.for_room_version(
1269
+ room_version_obj,
1270
+ {
1271
+ "type": EventTypes.Member,
1272
+ "content": {"membership": Membership.KNOCK},
1273
+ "room_id": room_id,
1274
+ "sender": user_id,
1275
+ "state_key": user_id,
1276
+ },
1277
+ )
1278
+
1279
+ (
1280
+ event,
1281
+ unpersisted_context,
1282
+ ) = await self.event_creation_handler.create_new_client_event(builder=builder)
1283
+
1284
+ event_allowed, _ = await self._third_party_event_rules.check_event_allowed(
1285
+ event, unpersisted_context
1286
+ )
1287
+ if not event_allowed:
1288
+ logger.warning("Creation of knock %s forbidden by third-party rules", event)
1289
+ raise SynapseError(
1290
+ 403, "This event is not allowed in this context", Codes.FORBIDDEN
1291
+ )
1292
+
1293
+ try:
1294
+ # The remote hasn't signed it yet, obviously. We'll do the full checks
1295
+ # when we get the event back in `on_send_knock_request`
1296
+ await self._event_auth_handler.check_auth_rules_from_context(event)
1297
+ except AuthError as e:
1298
+ logger.warning("Failed to create new knock %r because %s", event, e)
1299
+ raise e
1300
+
1301
+ return event
1302
+
1303
+ @trace
1304
+ @tag_args
1305
+ async def get_state_ids_for_pdu(self, room_id: str, event_id: str) -> list[str]:
1306
+ """Returns the state at the event. i.e. not including said event."""
1307
+ event = await self.store.get_event(event_id, check_room_id=room_id)
1308
+ if event.internal_metadata.outlier:
1309
+ raise NotFoundError("State not known at event %s" % (event_id,))
1310
+
1311
+ state_groups = await self._state_storage_controller.get_state_groups_ids(
1312
+ room_id, [event_id]
1313
+ )
1314
+
1315
+ # get_state_groups_ids should return exactly one result
1316
+ assert len(state_groups) == 1
1317
+
1318
+ state_map = next(iter(state_groups.values()))
1319
+
1320
+ state_key = event.get_state_key()
1321
+ if state_key is not None:
1322
+ # the event was not rejected (get_event raises a NotFoundError for rejected
1323
+ # events) so the state at the event should include the event itself.
1324
+ assert state_map.get((event.type, state_key)) == event.event_id, (
1325
+ "State at event did not include event itself"
1326
+ )
1327
+
1328
+ # ... but we need the state *before* that event
1329
+ if "replaces_state" in event.unsigned:
1330
+ prev_id = event.unsigned["replaces_state"]
1331
+ state_map[(event.type, state_key)] = prev_id
1332
+ else:
1333
+ del state_map[(event.type, state_key)]
1334
+
1335
+ return list(state_map.values())
1336
+
1337
+ async def on_backfill_request(
1338
+ self, origin: str, room_id: str, pdu_list: list[str], limit: int
1339
+ ) -> list[EventBase]:
1340
+ # We allow partially joined rooms since in this case we are filtering out
1341
+ # non-local events in `filter_events_for_server`.
1342
+ await self._event_auth_handler.assert_host_in_room(room_id, origin, True)
1343
+
1344
+ # Synapse asks for 100 events per backfill request. Do not allow more.
1345
+ limit = min(limit, 100)
1346
+
1347
+ events = await self.store.get_backfill_events(room_id, pdu_list, limit)
1348
+ logger.debug(
1349
+ "on_backfill_request: backfill events=%s",
1350
+ [
1351
+ "event_id=%s,depth=%d,body=%s,prevs=%s\n"
1352
+ % (
1353
+ event.event_id,
1354
+ event.depth,
1355
+ event.content.get("body", event.type),
1356
+ event.prev_event_ids(),
1357
+ )
1358
+ for event in events
1359
+ ],
1360
+ )
1361
+
1362
+ events = await filter_events_for_server(
1363
+ self._storage_controllers,
1364
+ origin,
1365
+ self.server_name,
1366
+ events,
1367
+ redact=True,
1368
+ filter_out_erased_senders=True,
1369
+ filter_out_remote_partial_state_events=True,
1370
+ )
1371
+
1372
+ return events
1373
+
1374
+ async def get_persisted_pdu(
1375
+ self, origin: str, event_id: str
1376
+ ) -> Optional[EventBase]:
1377
+ """Get an event from the database for the given server.
1378
+
1379
+ Args:
1380
+ origin: hostname of server which is requesting the event; we
1381
+ will check that the server is allowed to see it.
1382
+ event_id: id of the event being requested
1383
+
1384
+ Returns:
1385
+ None if we know nothing about the event; otherwise the (possibly-redacted) event.
1386
+
1387
+ Raises:
1388
+ AuthError if the server is not currently in the room
1389
+ """
1390
+ event = await self.store.get_event(
1391
+ event_id, allow_none=True, allow_rejected=True
1392
+ )
1393
+
1394
+ if not event:
1395
+ return None
1396
+
1397
+ await self._event_auth_handler.assert_host_in_room(event.room_id, origin)
1398
+
1399
+ events = await filter_events_for_server(
1400
+ self._storage_controllers,
1401
+ origin,
1402
+ self.server_name,
1403
+ [event],
1404
+ redact=True,
1405
+ filter_out_erased_senders=True,
1406
+ filter_out_remote_partial_state_events=True,
1407
+ )
1408
+ event = events[0]
1409
+ return event
1410
+
1411
+ async def on_get_missing_events(
1412
+ self,
1413
+ origin: str,
1414
+ room_id: str,
1415
+ earliest_events: list[str],
1416
+ latest_events: list[str],
1417
+ limit: int,
1418
+ ) -> list[EventBase]:
1419
+ # We allow partially joined rooms since in this case we are filtering out
1420
+ # non-local events in `filter_events_for_server`.
1421
+ await self._event_auth_handler.assert_host_in_room(room_id, origin, True)
1422
+
1423
+ # Only allow up to 20 events to be retrieved per request.
1424
+ limit = min(limit, 20)
1425
+
1426
+ missing_events = await self.store.get_missing_events(
1427
+ room_id=room_id,
1428
+ earliest_events=earliest_events,
1429
+ latest_events=latest_events,
1430
+ limit=limit,
1431
+ )
1432
+
1433
+ missing_events = await filter_events_for_server(
1434
+ self._storage_controllers,
1435
+ origin,
1436
+ self.server_name,
1437
+ missing_events,
1438
+ redact=True,
1439
+ filter_out_erased_senders=True,
1440
+ filter_out_remote_partial_state_events=True,
1441
+ )
1442
+
1443
+ return missing_events
1444
+
1445
+ async def exchange_third_party_invite(
1446
+ self, sender_user_id: str, target_user_id: str, room_id: str, signed: JsonDict
1447
+ ) -> None:
1448
+ third_party_invite = {"signed": signed}
1449
+
1450
+ event_dict = {
1451
+ "type": EventTypes.Member,
1452
+ "content": {
1453
+ "membership": Membership.INVITE,
1454
+ "third_party_invite": third_party_invite,
1455
+ },
1456
+ "room_id": room_id,
1457
+ "sender": sender_user_id,
1458
+ "state_key": target_user_id,
1459
+ }
1460
+
1461
+ if await self._event_auth_handler.is_host_in_room(room_id, self.hs.hostname):
1462
+ room_version_obj = await self.store.get_room_version(room_id)
1463
+ builder = self.event_builder_factory.for_room_version(
1464
+ room_version_obj, event_dict
1465
+ )
1466
+
1467
+ EventValidator().validate_builder(builder)
1468
+
1469
+ # Try several times, it could fail with PartialStateConflictError
1470
+ # in send_membership_event, cf comment in except block.
1471
+ max_retries = 5
1472
+ for i in range(max_retries):
1473
+ try:
1474
+ (
1475
+ event,
1476
+ unpersisted_context,
1477
+ ) = await self.event_creation_handler.create_new_client_event(
1478
+ builder=builder
1479
+ )
1480
+
1481
+ (
1482
+ event,
1483
+ unpersisted_context,
1484
+ ) = await self.add_display_name_to_third_party_invite(
1485
+ room_version_obj, event_dict, event, unpersisted_context
1486
+ )
1487
+
1488
+ context = await unpersisted_context.persist(event)
1489
+
1490
+ EventValidator().validate_new(event, self.config)
1491
+
1492
+ # We need to tell the transaction queue to send this out, even
1493
+ # though the sender isn't a local user.
1494
+ event.internal_metadata.send_on_behalf_of = self.hs.hostname
1495
+
1496
+ try:
1497
+ validate_event_for_room_version(event)
1498
+ await self._event_auth_handler.check_auth_rules_from_context(
1499
+ event
1500
+ )
1501
+ except AuthError as e:
1502
+ logger.warning(
1503
+ "Denying new third party invite %r because %s", event, e
1504
+ )
1505
+ raise e
1506
+
1507
+ await self._check_signature(event, context)
1508
+
1509
+ # We retrieve the room member handler here as to not cause a cyclic dependency
1510
+ member_handler = self.hs.get_room_member_handler()
1511
+ await member_handler.send_membership_event(None, event, context)
1512
+
1513
+ break
1514
+ except PartialStateConflictError as e:
1515
+ # Persisting couldn't happen because the room got un-partial stated
1516
+ # in the meantime and context needs to be recomputed, so let's do so.
1517
+ if i == max_retries - 1:
1518
+ raise e
1519
+ else:
1520
+ destinations = {x.split(":", 1)[-1] for x in (sender_user_id, room_id)}
1521
+
1522
+ try:
1523
+ await self.federation_client.forward_third_party_invite(
1524
+ destinations, room_id, event_dict
1525
+ )
1526
+ except (RequestSendFailed, HttpResponseException):
1527
+ raise SynapseError(502, "Failed to forward third party invite")
1528
+
1529
+ async def on_exchange_third_party_invite_request(
1530
+ self, event_dict: JsonDict
1531
+ ) -> None:
1532
+ """Handle an exchange_third_party_invite request from a remote server
1533
+
1534
+ The remote server will call this when it wants to turn a 3pid invite
1535
+ into a normal m.room.member invite.
1536
+
1537
+ Args:
1538
+ event_dict: Dictionary containing the event body.
1539
+
1540
+ """
1541
+ assert_params_in_dict(event_dict, ["room_id"])
1542
+ room_version_obj = await self.store.get_room_version(event_dict["room_id"])
1543
+
1544
+ # NB: event_dict has a particular specced format we might need to fudge
1545
+ # if we change event formats too much.
1546
+ builder = self.event_builder_factory.for_room_version(
1547
+ room_version_obj, event_dict
1548
+ )
1549
+
1550
+ # Try several times, it could fail with PartialStateConflictError
1551
+ # in send_membership_event, cf comment in except block.
1552
+ max_retries = 5
1553
+ for i in range(max_retries):
1554
+ try:
1555
+ (
1556
+ event,
1557
+ unpersisted_context,
1558
+ ) = await self.event_creation_handler.create_new_client_event(
1559
+ builder=builder
1560
+ )
1561
+ (
1562
+ event,
1563
+ unpersisted_context,
1564
+ ) = await self.add_display_name_to_third_party_invite(
1565
+ room_version_obj, event_dict, event, unpersisted_context
1566
+ )
1567
+
1568
+ context = await unpersisted_context.persist(event)
1569
+
1570
+ try:
1571
+ validate_event_for_room_version(event)
1572
+ await self._event_auth_handler.check_auth_rules_from_context(event)
1573
+ except AuthError as e:
1574
+ logger.warning("Denying third party invite %r because %s", event, e)
1575
+ raise e
1576
+ await self._check_signature(event, context)
1577
+
1578
+ # We need to tell the transaction queue to send this out, even
1579
+ # though the sender isn't a local user.
1580
+ event.internal_metadata.send_on_behalf_of = get_domain_from_id(
1581
+ event.sender
1582
+ )
1583
+
1584
+ # We retrieve the room member handler here as to not cause a cyclic dependency
1585
+ member_handler = self.hs.get_room_member_handler()
1586
+ await member_handler.send_membership_event(None, event, context)
1587
+
1588
+ break
1589
+ except PartialStateConflictError as e:
1590
+ # Persisting couldn't happen because the room got un-partial stated
1591
+ # in the meantime and context needs to be recomputed, so let's do so.
1592
+ if i == max_retries - 1:
1593
+ raise e
1594
+
1595
+ async def add_display_name_to_third_party_invite(
1596
+ self,
1597
+ room_version_obj: RoomVersion,
1598
+ event_dict: JsonDict,
1599
+ event: EventBase,
1600
+ context: UnpersistedEventContextBase,
1601
+ ) -> tuple[EventBase, UnpersistedEventContextBase]:
1602
+ key = (
1603
+ EventTypes.ThirdPartyInvite,
1604
+ event.content["third_party_invite"]["signed"]["token"],
1605
+ )
1606
+ original_invite = None
1607
+ prev_state_ids = await context.get_prev_state_ids(StateFilter.from_types([key]))
1608
+ original_invite_id = prev_state_ids.get(key)
1609
+ if original_invite_id:
1610
+ original_invite = await self.store.get_event(
1611
+ original_invite_id, allow_none=True
1612
+ )
1613
+ if original_invite:
1614
+ # If the m.room.third_party_invite event's content is empty, it means the
1615
+ # invite has been revoked. In this case, we don't have to raise an error here
1616
+ # because the auth check will fail on the invite (because it's not able to
1617
+ # fetch public keys from the m.room.third_party_invite event's content, which
1618
+ # is empty).
1619
+ display_name = original_invite.content.get("display_name")
1620
+ event_dict["content"]["third_party_invite"]["display_name"] = display_name
1621
+ else:
1622
+ logger.info(
1623
+ "Could not find invite event for third_party_invite: %r", event_dict
1624
+ )
1625
+ # We don't discard here as this is not the appropriate place to do
1626
+ # auth checks. If we need the invite and don't have it then the
1627
+ # auth check code will explode appropriately.
1628
+
1629
+ builder = self.event_builder_factory.for_room_version(
1630
+ room_version_obj, event_dict
1631
+ )
1632
+ EventValidator().validate_builder(builder)
1633
+
1634
+ (
1635
+ event,
1636
+ unpersisted_context,
1637
+ ) = await self.event_creation_handler.create_new_client_event(builder=builder)
1638
+
1639
+ EventValidator().validate_new(event, self.config)
1640
+ return event, unpersisted_context
1641
+
1642
+ async def _check_signature(self, event: EventBase, context: EventContext) -> None:
1643
+ """
1644
+ Checks that the signature in the event is consistent with its invite.
1645
+
1646
+ Args:
1647
+ event: The m.room.member event to check
1648
+ context:
1649
+
1650
+ Raises:
1651
+ AuthError: if signature didn't match any keys, or key has been
1652
+ revoked,
1653
+ SynapseError: if a transient error meant a key couldn't be checked
1654
+ for revocation.
1655
+ """
1656
+ signed = event.content["third_party_invite"]["signed"]
1657
+ token = signed["token"]
1658
+
1659
+ prev_state_ids = await context.get_prev_state_ids(
1660
+ StateFilter.from_types([(EventTypes.ThirdPartyInvite, token)])
1661
+ )
1662
+ invite_event_id = prev_state_ids.get((EventTypes.ThirdPartyInvite, token))
1663
+
1664
+ invite_event = None
1665
+ if invite_event_id:
1666
+ invite_event = await self.store.get_event(invite_event_id, allow_none=True)
1667
+
1668
+ if not invite_event:
1669
+ raise AuthError(403, "Could not find invite")
1670
+
1671
+ logger.debug("Checking auth on event %r", event.content)
1672
+
1673
+ last_exception: Optional[Exception] = None
1674
+
1675
+ # for each public key in the 3pid invite event
1676
+ for public_key_object in event_auth.get_public_keys(invite_event):
1677
+ try:
1678
+ # for each sig on the third_party_invite block of the actual invite
1679
+ for server, signature_block in signed["signatures"].items():
1680
+ for key_name in signature_block.keys():
1681
+ if not key_name.startswith("ed25519:"):
1682
+ continue
1683
+
1684
+ logger.debug(
1685
+ "Attempting to verify sig with key %s from %r "
1686
+ "against pubkey %r",
1687
+ key_name,
1688
+ server,
1689
+ public_key_object,
1690
+ )
1691
+
1692
+ try:
1693
+ public_key = public_key_object["public_key"]
1694
+ verify_key = decode_verify_key_bytes(
1695
+ key_name, decode_base64(public_key)
1696
+ )
1697
+ verify_signed_json(signed, server, verify_key)
1698
+ logger.debug(
1699
+ "Successfully verified sig with key %s from %r "
1700
+ "against pubkey %r",
1701
+ key_name,
1702
+ server,
1703
+ public_key_object,
1704
+ )
1705
+ except Exception:
1706
+ logger.info(
1707
+ "Failed to verify sig with key %s from %r "
1708
+ "against pubkey %r",
1709
+ key_name,
1710
+ server,
1711
+ public_key_object,
1712
+ )
1713
+ raise
1714
+ try:
1715
+ if "key_validity_url" in public_key_object:
1716
+ await self._check_key_revocation(
1717
+ public_key, public_key_object["key_validity_url"]
1718
+ )
1719
+ except Exception:
1720
+ logger.info(
1721
+ "Failed to query key_validity_url %s",
1722
+ public_key_object["key_validity_url"],
1723
+ )
1724
+ raise
1725
+ return
1726
+ except Exception as e:
1727
+ last_exception = e
1728
+
1729
+ if last_exception is None:
1730
+ # we can only get here if get_public_keys() returned an empty list
1731
+ # TODO: make this better
1732
+ raise RuntimeError("no public key in invite event")
1733
+
1734
+ raise last_exception
1735
+
1736
+ async def _check_key_revocation(self, public_key: str, url: str) -> None:
1737
+ """
1738
+ Checks whether public_key has been revoked.
1739
+
1740
+ Args:
1741
+ public_key: base-64 encoded public key.
1742
+ url: Key revocation URL.
1743
+
1744
+ Raises:
1745
+ AuthError: if they key has been revoked.
1746
+ SynapseError: if a transient error meant a key couldn't be checked
1747
+ for revocation.
1748
+ """
1749
+ try:
1750
+ response = await self.http_client.get_json(url, {"public_key": public_key})
1751
+ except Exception:
1752
+ raise SynapseError(502, "Third party certificate could not be checked")
1753
+ if "valid" not in response or not response["valid"]:
1754
+ raise AuthError(403, "Third party certificate was invalid")
1755
+
1756
+ async def get_room_complexity(
1757
+ self, remote_room_hosts: list[str], room_id: str
1758
+ ) -> Optional[dict]:
1759
+ """
1760
+ Fetch the complexity of a remote room over federation.
1761
+
1762
+ Args:
1763
+ remote_room_hosts: The remote servers to ask.
1764
+ room_id: The room ID to ask about.
1765
+
1766
+ Returns:
1767
+ Dict contains the complexity
1768
+ metric versions, while None means we could not fetch the complexity.
1769
+ """
1770
+
1771
+ for host in remote_room_hosts:
1772
+ res = await self.federation_client.get_room_complexity(host, room_id)
1773
+
1774
+ # We got a result, return it.
1775
+ if res:
1776
+ return res
1777
+
1778
+ # We fell off the bottom, couldn't get the complexity from anyone. Oh
1779
+ # well.
1780
+ return None
1781
+
1782
+ async def _resume_partial_state_room_sync(self) -> None:
1783
+ """Resumes resyncing of all partial-state rooms after a restart."""
1784
+ assert not self.config.worker.worker_app
1785
+
1786
+ partial_state_rooms = await self.store.get_partial_state_room_resync_info()
1787
+ for room_id, resync_info in partial_state_rooms.items():
1788
+ self._start_partial_state_room_sync(
1789
+ initial_destination=resync_info.joined_via,
1790
+ other_destinations=resync_info.servers_in_room,
1791
+ room_id=room_id,
1792
+ )
1793
+
1794
+ def _start_partial_state_room_sync(
1795
+ self,
1796
+ initial_destination: Optional[str],
1797
+ other_destinations: AbstractSet[str],
1798
+ room_id: str,
1799
+ ) -> None:
1800
+ """Starts the background process to resync the state of a partial state room,
1801
+ if it is not already running.
1802
+
1803
+ Args:
1804
+ initial_destination: the initial homeserver to pull the state from
1805
+ other_destinations: other homeservers to try to pull the state from, if
1806
+ `initial_destination` is unavailable
1807
+ room_id: room to be resynced
1808
+ """
1809
+
1810
+ async def _sync_partial_state_room_wrapper() -> None:
1811
+ if room_id in self._active_partial_state_syncs:
1812
+ # Another local user has joined the room while there is already a
1813
+ # partial state sync running. This implies that there is a new join
1814
+ # event to un-partial state. We might find ourselves in one of a few
1815
+ # scenarios:
1816
+ # 1. There is an existing partial state sync. The partial state sync
1817
+ # un-partial states the new join event before completing and all is
1818
+ # well.
1819
+ # 2. Before the latest join, the homeserver was no longer in the room
1820
+ # and there is an existing partial state sync from our previous
1821
+ # membership of the room. The partial state sync may have:
1822
+ # a) succeeded, but not yet terminated. The room will not be
1823
+ # un-partial stated again unless we restart the partial state
1824
+ # sync.
1825
+ # b) failed, because we were no longer in the room and remote
1826
+ # homeservers were refusing our requests, but not yet
1827
+ # terminated. After the latest join, remote homeservers may
1828
+ # start answering our requests again, so we should restart the
1829
+ # partial state sync.
1830
+ # In the cases where we would want to restart the partial state sync,
1831
+ # the room would have the partial state flag when the partial state sync
1832
+ # terminates.
1833
+ self._partial_state_syncs_maybe_needing_restart[room_id] = (
1834
+ initial_destination,
1835
+ other_destinations,
1836
+ )
1837
+ return
1838
+
1839
+ self._active_partial_state_syncs.add(room_id)
1840
+
1841
+ try:
1842
+ await self._sync_partial_state_room(
1843
+ initial_destination=initial_destination,
1844
+ other_destinations=other_destinations,
1845
+ room_id=room_id,
1846
+ )
1847
+ finally:
1848
+ # Read the room's partial state flag while we still hold the claim to
1849
+ # being the active partial state sync (so that another partial state
1850
+ # sync can't come along and mess with it under us).
1851
+ # Normally, the partial state flag will be gone. If it isn't, then we
1852
+ # may find ourselves in scenario 2a or 2b as described in the comment
1853
+ # above, where we want to restart the partial state sync.
1854
+ is_still_partial_state_room = await self.store.is_partial_state_room(
1855
+ room_id
1856
+ )
1857
+ self._active_partial_state_syncs.remove(room_id)
1858
+
1859
+ if room_id in self._partial_state_syncs_maybe_needing_restart:
1860
+ (
1861
+ restart_initial_destination,
1862
+ restart_other_destinations,
1863
+ ) = self._partial_state_syncs_maybe_needing_restart.pop(room_id)
1864
+
1865
+ if is_still_partial_state_room:
1866
+ self._start_partial_state_room_sync(
1867
+ initial_destination=restart_initial_destination,
1868
+ other_destinations=restart_other_destinations,
1869
+ room_id=room_id,
1870
+ )
1871
+
1872
+ self.hs.run_as_background_process(
1873
+ desc="sync_partial_state_room",
1874
+ func=_sync_partial_state_room_wrapper,
1875
+ )
1876
+
1877
+ async def _sync_partial_state_room(
1878
+ self,
1879
+ initial_destination: Optional[str],
1880
+ other_destinations: AbstractSet[str],
1881
+ room_id: str,
1882
+ ) -> None:
1883
+ """Background process to resync the state of a partial-state room
1884
+
1885
+ Args:
1886
+ initial_destination: the initial homeserver to pull the state from
1887
+ other_destinations: other homeservers to try to pull the state from, if
1888
+ `initial_destination` is unavailable
1889
+ room_id: room to be resynced
1890
+ """
1891
+ # Assume that we run on the main process for now.
1892
+ # TODO(faster_joins,multiple workers)
1893
+ # When moving the sync to workers, we need to ensure that
1894
+ # * `_start_partial_state_room_sync` still prevents duplicate resyncs
1895
+ # * `_is_partial_state_room_linearizer` correctly guards partial state flags
1896
+ # for rooms between the workers doing remote joins and resync.
1897
+ assert not self.config.worker.worker_app
1898
+
1899
+ # TODO(faster_joins): do we need to lock to avoid races? What happens if other
1900
+ # worker processes kick off a resync in parallel? Perhaps we should just elect
1901
+ # a single worker to do the resync.
1902
+ # https://github.com/matrix-org/synapse/issues/12994
1903
+ #
1904
+ # TODO(faster_joins): what happens if we leave the room during a resync? if we
1905
+ # really leave, that might mean we have difficulty getting the room state over
1906
+ # federation.
1907
+ # https://github.com/matrix-org/synapse/issues/12802
1908
+
1909
+ # Make an infinite iterator of destinations to try. Once we find a working
1910
+ # destination, we'll stick with it until it flakes.
1911
+ destinations = _prioritise_destinations_for_partial_state_resync(
1912
+ initial_destination, other_destinations, room_id
1913
+ )
1914
+ destination_iter = itertools.cycle(destinations)
1915
+
1916
+ # `destination` is the current remote homeserver we're pulling from.
1917
+ destination = next(destination_iter)
1918
+ logger.info("Syncing state for room %s via %s", room_id, destination)
1919
+
1920
+ # we work through the queue in order of increasing stream ordering.
1921
+ while True:
1922
+ batch = await self.store.get_partial_state_events_batch(room_id)
1923
+ if not batch:
1924
+ # all the events are updated, so we can update current state and
1925
+ # clear the lazy-loading flag.
1926
+ logger.info("Updating current state for %s", room_id)
1927
+ # TODO(faster_joins): notify workers in notify_room_un_partial_stated
1928
+ # https://github.com/matrix-org/synapse/issues/12994
1929
+ #
1930
+ # NB: there's a potential race here. If room is purged just before we
1931
+ # call this, we _might_ end up inserting rows into current_state_events.
1932
+ # (The logic is hard to chase through.) We think this is fine, but if
1933
+ # not the HS admin should purge the room again.
1934
+ await self.state_handler.update_current_state(room_id)
1935
+
1936
+ logger.info("Handling any pending device list updates")
1937
+ await self._device_handler.handle_room_un_partial_stated(room_id)
1938
+
1939
+ async with self._is_partial_state_room_linearizer.queue(room_id):
1940
+ logger.info("Clearing partial-state flag for %s", room_id)
1941
+ new_stream_id = await self.store.clear_partial_state_room(room_id)
1942
+
1943
+ if new_stream_id is not None:
1944
+ logger.info("State resync complete for %s", room_id)
1945
+ self._storage_controllers.state.notify_room_un_partial_stated(
1946
+ room_id
1947
+ )
1948
+
1949
+ await self._notifier.on_un_partial_stated_room(
1950
+ room_id, new_stream_id
1951
+ )
1952
+ return
1953
+
1954
+ # we raced against more events arriving with partial state. Go round
1955
+ # the loop again. We've already logged a warning, so no need for more.
1956
+ continue
1957
+
1958
+ events = await self.store.get_events_as_list(
1959
+ batch,
1960
+ redact_behaviour=EventRedactBehaviour.as_is,
1961
+ allow_rejected=True,
1962
+ )
1963
+ for event in events:
1964
+ for attempt in itertools.count():
1965
+ # We try a new destination on every iteration.
1966
+ try:
1967
+ while True:
1968
+ try:
1969
+ await self._federation_event_handler.update_state_for_partial_state_event(
1970
+ destination, event
1971
+ )
1972
+ break
1973
+ except FederationPullAttemptBackoffError as e:
1974
+ # We are in the backoff period for one of the event's
1975
+ # prev_events. Wait it out and try again after.
1976
+ logger.warning(
1977
+ "%s; waiting for %d ms...", e, e.retry_after_ms
1978
+ )
1979
+ await self.clock.sleep(e.retry_after_ms / 1000)
1980
+
1981
+ # Success, no need to try the rest of the destinations.
1982
+ break
1983
+ except FederationError as e:
1984
+ if attempt == len(destinations) - 1:
1985
+ # We have tried every remote server for this event. Give up.
1986
+ # TODO(faster_joins) giving up isn't the right thing to do
1987
+ # if there's a temporary network outage. retrying
1988
+ # indefinitely is also not the right thing to do if we can
1989
+ # reach all homeservers and they all claim they don't have
1990
+ # the state we want.
1991
+ # https://github.com/matrix-org/synapse/issues/13000
1992
+ logger.error(
1993
+ "Failed to get state for %s at %s from %s because %s, "
1994
+ "giving up!",
1995
+ room_id,
1996
+ event,
1997
+ destination,
1998
+ e,
1999
+ )
2000
+ # TODO: We should `record_event_failed_pull_attempt` here,
2001
+ # see https://github.com/matrix-org/synapse/issues/13700
2002
+ raise
2003
+
2004
+ # Try the next remote server.
2005
+ logger.info(
2006
+ "Failed to get state for %s at %s from %s because %s",
2007
+ room_id,
2008
+ event,
2009
+ destination,
2010
+ e,
2011
+ )
2012
+ destination = next(destination_iter)
2013
+ logger.info(
2014
+ "Syncing state for room %s via %s instead",
2015
+ room_id,
2016
+ destination,
2017
+ )
2018
+
2019
+
2020
+ def _prioritise_destinations_for_partial_state_resync(
2021
+ initial_destination: Optional[str],
2022
+ other_destinations: AbstractSet[str],
2023
+ room_id: str,
2024
+ ) -> StrCollection:
2025
+ """Work out the order in which we should ask servers to resync events.
2026
+
2027
+ If an `initial_destination` is given, it takes top priority. Otherwise
2028
+ all servers are treated equally.
2029
+
2030
+ :raises ValueError: if no destination is provided at all.
2031
+ """
2032
+ if initial_destination is None and len(other_destinations) == 0:
2033
+ raise ValueError(f"Cannot resync state of {room_id}: no destinations provided")
2034
+
2035
+ if initial_destination is None:
2036
+ return other_destinations
2037
+
2038
+ # Move `initial_destination` to the front of the list.
2039
+ destinations = list(other_destinations)
2040
+ if initial_destination in destinations:
2041
+ destinations.remove(initial_destination)
2042
+ destinations = [initial_destination] + destinations
2043
+ return destinations