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