matrix-synapse 1.145.0rc2__cp310-abi3-manylinux_2_28_x86_64.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 (1636) hide show
  1. AUTHORS.rst +51 -0
  2. CHANGES.md +1732 -0
  3. CONTRIBUTING.md +3 -0
  4. Cargo.lock +1923 -0
  5. Cargo.toml +6 -0
  6. INSTALL.md +7 -0
  7. LICENSE-AGPL-3.0 +661 -0
  8. LICENSE-COMMERCIAL +6 -0
  9. UPGRADE.rst +7 -0
  10. book.toml +47 -0
  11. changelog.d/.gitignore +1 -0
  12. demo/.gitignore +4 -0
  13. demo/clean.sh +22 -0
  14. demo/start.sh +173 -0
  15. demo/stop.sh +14 -0
  16. docs/.sample_config_header.yaml +12 -0
  17. docs/CAPTCHA_SETUP.md +37 -0
  18. docs/README.md +86 -0
  19. docs/SUMMARY.md +126 -0
  20. docs/admin_api/README.rst +13 -0
  21. docs/admin_api/account_validity.md +47 -0
  22. docs/admin_api/client_server_api_extensions.md +67 -0
  23. docs/admin_api/event_reports.md +185 -0
  24. docs/admin_api/experimental_features.md +52 -0
  25. docs/admin_api/fetch_event.md +53 -0
  26. docs/admin_api/media_admin_api.md +372 -0
  27. docs/admin_api/purge_history_api.md +77 -0
  28. docs/admin_api/register_api.md +92 -0
  29. docs/admin_api/room_membership.md +35 -0
  30. docs/admin_api/rooms.md +1190 -0
  31. docs/admin_api/scheduled_tasks.md +54 -0
  32. docs/admin_api/server_notices.md +48 -0
  33. docs/admin_api/statistics.md +132 -0
  34. docs/admin_api/user_admin_api.md +1602 -0
  35. docs/admin_api/version_api.md +23 -0
  36. docs/ancient_architecture_notes.md +81 -0
  37. docs/application_services.md +36 -0
  38. docs/architecture.md +65 -0
  39. docs/auth_chain_diff.dot +32 -0
  40. docs/auth_chain_diff.dot.png +0 -0
  41. docs/auth_chain_difference_algorithm.md +141 -0
  42. docs/changelogs/CHANGES-2019.md +1039 -0
  43. docs/changelogs/CHANGES-2020.md +2145 -0
  44. docs/changelogs/CHANGES-2021.md +2573 -0
  45. docs/changelogs/CHANGES-2022.md +2766 -0
  46. docs/changelogs/CHANGES-2023.md +2202 -0
  47. docs/changelogs/CHANGES-2024.md +1586 -0
  48. docs/changelogs/CHANGES-pre-1.0.md +3641 -0
  49. docs/changelogs/README.md +1 -0
  50. docs/code_style.md +119 -0
  51. docs/consent_tracking.md +197 -0
  52. docs/delegate.md +111 -0
  53. docs/deprecation_policy.md +89 -0
  54. docs/development/cas.md +64 -0
  55. docs/development/contributing_guide.md +554 -0
  56. docs/development/database_schema.md +404 -0
  57. docs/development/demo.md +42 -0
  58. docs/development/dependencies.md +326 -0
  59. docs/development/experimental_features.md +37 -0
  60. docs/development/git.md +148 -0
  61. docs/development/img/git/branches.jpg +0 -0
  62. docs/development/img/git/clean.png +0 -0
  63. docs/development/img/git/squash.png +0 -0
  64. docs/development/internal_documentation/README.md +12 -0
  65. docs/development/internal_documentation/release_notes_review_checklist.md +12 -0
  66. docs/development/releases.md +37 -0
  67. docs/development/reviews.md +41 -0
  68. docs/development/room-dag-concepts.md +115 -0
  69. docs/development/saml.md +40 -0
  70. docs/development/synapse_architecture/cancellation.md +392 -0
  71. docs/development/synapse_architecture/faster_joins.md +375 -0
  72. docs/development/synapse_architecture/streams.md +198 -0
  73. docs/element_logo_white_bg.svg +94 -0
  74. docs/favicon.png +0 -0
  75. docs/favicon.svg +58 -0
  76. docs/federate.md +67 -0
  77. docs/jwt.md +105 -0
  78. docs/log_contexts.md +566 -0
  79. docs/manhole.md +101 -0
  80. docs/media_repository.md +78 -0
  81. docs/message_retention_policies.md +207 -0
  82. docs/metrics-howto.md +315 -0
  83. docs/modules/account_data_callbacks.md +106 -0
  84. docs/modules/account_validity_callbacks.md +57 -0
  85. docs/modules/add_extra_fields_to_client_events_unsigned.md +32 -0
  86. docs/modules/background_update_controller_callbacks.md +71 -0
  87. docs/modules/index.md +53 -0
  88. docs/modules/media_repository_callbacks.md +131 -0
  89. docs/modules/password_auth_provider_callbacks.md +270 -0
  90. docs/modules/porting_legacy_module.md +20 -0
  91. docs/modules/presence_router_callbacks.md +112 -0
  92. docs/modules/ratelimit_callbacks.md +43 -0
  93. docs/modules/spam_checker_callbacks.md +517 -0
  94. docs/modules/third_party_rules_callbacks.md +350 -0
  95. docs/modules/writing_a_module.md +141 -0
  96. docs/openid.md +783 -0
  97. docs/opentracing.md +99 -0
  98. docs/other/running_synapse_on_single_board_computers.md +75 -0
  99. docs/password_auth_providers.md +129 -0
  100. docs/postgres.md +269 -0
  101. docs/presence_router_module.md +247 -0
  102. docs/privacy_policy_templates/en/1.0.html +26 -0
  103. docs/privacy_policy_templates/en/success.html +11 -0
  104. docs/replication.md +36 -0
  105. docs/reverse_proxy.md +327 -0
  106. docs/room_and_user_statistics.md +22 -0
  107. docs/sample_config.yaml +47 -0
  108. docs/sample_log_config.yaml +75 -0
  109. docs/server_notices.md +66 -0
  110. docs/setup/forward_proxy.md +89 -0
  111. docs/setup/installation.md +656 -0
  112. docs/setup/security.md +41 -0
  113. docs/setup/turn/coturn.md +197 -0
  114. docs/setup/turn/eturnal.md +170 -0
  115. docs/spam_checker.md +122 -0
  116. docs/sso_mapping_providers.md +208 -0
  117. docs/structured_logging.md +80 -0
  118. docs/synctl_workers.md +36 -0
  119. docs/systemd-with-workers/README.md +101 -0
  120. docs/systemd-with-workers/system/matrix-synapse-worker@.service +26 -0
  121. docs/systemd-with-workers/system/matrix-synapse.service +23 -0
  122. docs/systemd-with-workers/system/matrix-synapse.target +6 -0
  123. docs/systemd-with-workers/workers/background_worker.yaml +4 -0
  124. docs/systemd-with-workers/workers/event_persister.yaml +20 -0
  125. docs/systemd-with-workers/workers/federation_sender.yaml +4 -0
  126. docs/systemd-with-workers/workers/generic_worker.yaml +11 -0
  127. docs/systemd-with-workers/workers/media_worker.yaml +11 -0
  128. docs/systemd-with-workers/workers/pusher_worker.yaml +4 -0
  129. docs/tcp_replication.md +258 -0
  130. docs/templates.md +254 -0
  131. docs/turn-howto.md +168 -0
  132. docs/upgrade.md +2876 -0
  133. docs/usage/administration/README.md +7 -0
  134. docs/usage/administration/admin_api/README.md +47 -0
  135. docs/usage/administration/admin_api/background_updates.md +109 -0
  136. docs/usage/administration/admin_api/federation.md +212 -0
  137. docs/usage/administration/admin_api/registration_tokens.md +298 -0
  138. docs/usage/administration/admin_faq.md +294 -0
  139. docs/usage/administration/backups.md +125 -0
  140. docs/usage/administration/database_maintenance_tools.md +18 -0
  141. docs/usage/administration/monitoring/reporting_homeserver_usage_statistics.md +77 -0
  142. docs/usage/administration/monthly_active_users.md +84 -0
  143. docs/usage/administration/request_log.md +44 -0
  144. docs/usage/administration/state_groups.md +25 -0
  145. docs/usage/administration/understanding_synapse_through_grafana_graphs.md +83 -0
  146. docs/usage/administration/useful_sql_for_admins.md +216 -0
  147. docs/usage/configuration/README.md +4 -0
  148. docs/usage/configuration/config_documentation.md +4768 -0
  149. docs/usage/configuration/homeserver_sample_config.md +17 -0
  150. docs/usage/configuration/logging_sample_config.md +19 -0
  151. docs/usage/configuration/user_authentication/README.md +15 -0
  152. docs/usage/configuration/user_authentication/refresh_tokens.md +139 -0
  153. docs/usage/configuration/user_authentication/single_sign_on/README.md +5 -0
  154. docs/usage/configuration/user_authentication/single_sign_on/cas.md +8 -0
  155. docs/usage/configuration/user_authentication/single_sign_on/saml.md +8 -0
  156. docs/user_directory.md +130 -0
  157. docs/website_files/README.md +35 -0
  158. docs/website_files/indent-section-headers.css +7 -0
  159. docs/website_files/remove-nav-buttons.css +8 -0
  160. docs/website_files/table-of-contents.css +47 -0
  161. docs/website_files/table-of-contents.js +148 -0
  162. docs/website_files/theme/index.hbs +324 -0
  163. docs/website_files/version-picker.css +78 -0
  164. docs/website_files/version-picker.js +147 -0
  165. docs/website_files/version.js +1 -0
  166. docs/welcome_and_overview.md +67 -0
  167. docs/workers.md +897 -0
  168. matrix_synapse-1.145.0rc2.dist-info/METADATA +260 -0
  169. matrix_synapse-1.145.0rc2.dist-info/RECORD +1636 -0
  170. matrix_synapse-1.145.0rc2.dist-info/WHEEL +5 -0
  171. matrix_synapse-1.145.0rc2.dist-info/entry_points.txt +13 -0
  172. matrix_synapse-1.145.0rc2.dist-info/licenses/AUTHORS.rst +51 -0
  173. matrix_synapse-1.145.0rc2.dist-info/licenses/LICENSE-AGPL-3.0 +661 -0
  174. matrix_synapse-1.145.0rc2.dist-info/licenses/LICENSE-COMMERCIAL +6 -0
  175. mypy.ini +115 -0
  176. rust/Cargo.toml +63 -0
  177. rust/build.rs +45 -0
  178. scripts-dev/build_debian_packages.py +228 -0
  179. scripts-dev/check-newsfragment.sh +62 -0
  180. scripts-dev/check_line_terminators.sh +29 -0
  181. scripts-dev/check_locked_deps_have_sdists.py +64 -0
  182. scripts-dev/check_schema_delta.py +240 -0
  183. scripts-dev/complement.sh +332 -0
  184. scripts-dev/config-lint.sh +15 -0
  185. scripts-dev/database-save.sh +15 -0
  186. scripts-dev/docker_update_debian_changelog.sh +70 -0
  187. scripts-dev/dump_macaroon.py +25 -0
  188. scripts-dev/federation_client.py +428 -0
  189. scripts-dev/gen_config_documentation.py +510 -0
  190. scripts-dev/generate_sample_config.sh +28 -0
  191. scripts-dev/lint.sh +141 -0
  192. scripts-dev/make_full_schema.sh +310 -0
  193. scripts-dev/mypy_synapse_plugin.py +918 -0
  194. scripts-dev/next_github_number.sh +9 -0
  195. scripts-dev/release.py +986 -0
  196. scripts-dev/schema_versions.py +182 -0
  197. scripts-dev/sign_json.py +172 -0
  198. synapse/__init__.py +97 -0
  199. synapse/_scripts/__init__.py +0 -0
  200. synapse/_scripts/export_signing_key.py +109 -0
  201. synapse/_scripts/generate_config.py +83 -0
  202. synapse/_scripts/generate_log_config.py +56 -0
  203. synapse/_scripts/generate_signing_key.py +55 -0
  204. synapse/_scripts/generate_workers_map.py +318 -0
  205. synapse/_scripts/hash_password.py +95 -0
  206. synapse/_scripts/move_remote_media_to_new_store.py +128 -0
  207. synapse/_scripts/register_new_matrix_user.py +402 -0
  208. synapse/_scripts/review_recent_signups.py +212 -0
  209. synapse/_scripts/synapse_port_db.py +1604 -0
  210. synapse/_scripts/synctl.py +365 -0
  211. synapse/_scripts/update_synapse_database.py +130 -0
  212. synapse/api/__init__.py +20 -0
  213. synapse/api/auth/__init__.py +207 -0
  214. synapse/api/auth/base.py +406 -0
  215. synapse/api/auth/internal.py +299 -0
  216. synapse/api/auth/mas.py +436 -0
  217. synapse/api/auth/msc3861_delegated.py +617 -0
  218. synapse/api/auth_blocking.py +144 -0
  219. synapse/api/constants.py +379 -0
  220. synapse/api/errors.py +913 -0
  221. synapse/api/filtering.py +537 -0
  222. synapse/api/presence.py +102 -0
  223. synapse/api/ratelimiting.py +481 -0
  224. synapse/api/room_versions.py +535 -0
  225. synapse/api/urls.py +118 -0
  226. synapse/app/__init__.py +62 -0
  227. synapse/app/_base.py +906 -0
  228. synapse/app/admin_cmd.py +388 -0
  229. synapse/app/appservice.py +30 -0
  230. synapse/app/client_reader.py +30 -0
  231. synapse/app/complement_fork_starter.py +206 -0
  232. synapse/app/event_creator.py +29 -0
  233. synapse/app/federation_reader.py +30 -0
  234. synapse/app/federation_sender.py +30 -0
  235. synapse/app/frontend_proxy.py +30 -0
  236. synapse/app/generic_worker.py +475 -0
  237. synapse/app/homeserver.py +505 -0
  238. synapse/app/media_repository.py +30 -0
  239. synapse/app/phone_stats_home.py +292 -0
  240. synapse/app/pusher.py +30 -0
  241. synapse/app/synchrotron.py +30 -0
  242. synapse/app/user_dir.py +31 -0
  243. synapse/appservice/__init__.py +458 -0
  244. synapse/appservice/api.py +567 -0
  245. synapse/appservice/scheduler.py +565 -0
  246. synapse/config/__init__.py +27 -0
  247. synapse/config/__main__.py +62 -0
  248. synapse/config/_base.py +1154 -0
  249. synapse/config/_base.pyi +216 -0
  250. synapse/config/_util.py +99 -0
  251. synapse/config/account_validity.py +116 -0
  252. synapse/config/api.py +141 -0
  253. synapse/config/appservice.py +210 -0
  254. synapse/config/auth.py +80 -0
  255. synapse/config/auto_accept_invites.py +43 -0
  256. synapse/config/background_updates.py +44 -0
  257. synapse/config/cache.py +231 -0
  258. synapse/config/captcha.py +90 -0
  259. synapse/config/cas.py +116 -0
  260. synapse/config/consent.py +73 -0
  261. synapse/config/database.py +184 -0
  262. synapse/config/emailconfig.py +367 -0
  263. synapse/config/experimental.py +601 -0
  264. synapse/config/federation.py +114 -0
  265. synapse/config/homeserver.py +141 -0
  266. synapse/config/jwt.py +55 -0
  267. synapse/config/key.py +447 -0
  268. synapse/config/logger.py +390 -0
  269. synapse/config/mas.py +192 -0
  270. synapse/config/matrixrtc.py +66 -0
  271. synapse/config/metrics.py +93 -0
  272. synapse/config/modules.py +40 -0
  273. synapse/config/oembed.py +185 -0
  274. synapse/config/oidc.py +509 -0
  275. synapse/config/password_auth_providers.py +82 -0
  276. synapse/config/push.py +64 -0
  277. synapse/config/ratelimiting.py +260 -0
  278. synapse/config/redis.py +74 -0
  279. synapse/config/registration.py +296 -0
  280. synapse/config/repository.py +311 -0
  281. synapse/config/retention.py +162 -0
  282. synapse/config/room.py +88 -0
  283. synapse/config/room_directory.py +165 -0
  284. synapse/config/saml2.py +251 -0
  285. synapse/config/server.py +1139 -0
  286. synapse/config/server_notices.py +84 -0
  287. synapse/config/spam_checker.py +66 -0
  288. synapse/config/sso.py +121 -0
  289. synapse/config/stats.py +54 -0
  290. synapse/config/third_party_event_rules.py +40 -0
  291. synapse/config/tls.py +192 -0
  292. synapse/config/tracer.py +71 -0
  293. synapse/config/user_directory.py +47 -0
  294. synapse/config/user_types.py +42 -0
  295. synapse/config/voip.py +59 -0
  296. synapse/config/workers.py +642 -0
  297. synapse/crypto/__init__.py +20 -0
  298. synapse/crypto/context_factory.py +278 -0
  299. synapse/crypto/event_signing.py +194 -0
  300. synapse/crypto/keyring.py +980 -0
  301. synapse/event_auth.py +1266 -0
  302. synapse/events/__init__.py +667 -0
  303. synapse/events/auto_accept_invites.py +216 -0
  304. synapse/events/builder.py +387 -0
  305. synapse/events/presence_router.py +243 -0
  306. synapse/events/snapshot.py +559 -0
  307. synapse/events/utils.py +924 -0
  308. synapse/events/validator.py +305 -0
  309. synapse/federation/__init__.py +22 -0
  310. synapse/federation/federation_base.py +382 -0
  311. synapse/federation/federation_client.py +2133 -0
  312. synapse/federation/federation_server.py +1543 -0
  313. synapse/federation/persistence.py +70 -0
  314. synapse/federation/send_queue.py +532 -0
  315. synapse/federation/sender/__init__.py +1165 -0
  316. synapse/federation/sender/per_destination_queue.py +886 -0
  317. synapse/federation/sender/transaction_manager.py +210 -0
  318. synapse/federation/transport/__init__.py +28 -0
  319. synapse/federation/transport/client.py +1199 -0
  320. synapse/federation/transport/server/__init__.py +334 -0
  321. synapse/federation/transport/server/_base.py +429 -0
  322. synapse/federation/transport/server/federation.py +910 -0
  323. synapse/federation/units.py +133 -0
  324. synapse/handlers/__init__.py +20 -0
  325. synapse/handlers/account.py +162 -0
  326. synapse/handlers/account_data.py +360 -0
  327. synapse/handlers/account_validity.py +362 -0
  328. synapse/handlers/admin.py +615 -0
  329. synapse/handlers/appservice.py +989 -0
  330. synapse/handlers/auth.py +2482 -0
  331. synapse/handlers/cas.py +413 -0
  332. synapse/handlers/deactivate_account.py +363 -0
  333. synapse/handlers/delayed_events.py +607 -0
  334. synapse/handlers/device.py +1869 -0
  335. synapse/handlers/devicemessage.py +399 -0
  336. synapse/handlers/directory.py +545 -0
  337. synapse/handlers/e2e_keys.py +1835 -0
  338. synapse/handlers/e2e_room_keys.py +455 -0
  339. synapse/handlers/event_auth.py +390 -0
  340. synapse/handlers/events.py +203 -0
  341. synapse/handlers/federation.py +2042 -0
  342. synapse/handlers/federation_event.py +2420 -0
  343. synapse/handlers/identity.py +812 -0
  344. synapse/handlers/initial_sync.py +528 -0
  345. synapse/handlers/jwt.py +120 -0
  346. synapse/handlers/message.py +2357 -0
  347. synapse/handlers/oidc.py +1801 -0
  348. synapse/handlers/pagination.py +811 -0
  349. synapse/handlers/password_policy.py +102 -0
  350. synapse/handlers/presence.py +2634 -0
  351. synapse/handlers/profile.py +656 -0
  352. synapse/handlers/push_rules.py +164 -0
  353. synapse/handlers/read_marker.py +79 -0
  354. synapse/handlers/receipts.py +351 -0
  355. synapse/handlers/register.py +1059 -0
  356. synapse/handlers/relations.py +623 -0
  357. synapse/handlers/reports.py +98 -0
  358. synapse/handlers/room.py +2449 -0
  359. synapse/handlers/room_list.py +632 -0
  360. synapse/handlers/room_member.py +2366 -0
  361. synapse/handlers/room_member_worker.py +146 -0
  362. synapse/handlers/room_policy.py +186 -0
  363. synapse/handlers/room_summary.py +1057 -0
  364. synapse/handlers/saml.py +524 -0
  365. synapse/handlers/search.py +723 -0
  366. synapse/handlers/send_email.py +209 -0
  367. synapse/handlers/set_password.py +71 -0
  368. synapse/handlers/sliding_sync/__init__.py +1961 -0
  369. synapse/handlers/sliding_sync/extensions.py +969 -0
  370. synapse/handlers/sliding_sync/room_lists.py +2317 -0
  371. synapse/handlers/sliding_sync/store.py +126 -0
  372. synapse/handlers/sso.py +1291 -0
  373. synapse/handlers/state_deltas.py +82 -0
  374. synapse/handlers/stats.py +322 -0
  375. synapse/handlers/sync.py +3096 -0
  376. synapse/handlers/thread_subscriptions.py +190 -0
  377. synapse/handlers/typing.py +612 -0
  378. synapse/handlers/ui_auth/__init__.py +48 -0
  379. synapse/handlers/ui_auth/checkers.py +332 -0
  380. synapse/handlers/user_directory.py +786 -0
  381. synapse/handlers/worker_lock.py +371 -0
  382. synapse/http/__init__.py +105 -0
  383. synapse/http/additional_resource.py +62 -0
  384. synapse/http/client.py +1377 -0
  385. synapse/http/connectproxyclient.py +316 -0
  386. synapse/http/federation/__init__.py +19 -0
  387. synapse/http/federation/matrix_federation_agent.py +490 -0
  388. synapse/http/federation/srv_resolver.py +196 -0
  389. synapse/http/federation/well_known_resolver.py +368 -0
  390. synapse/http/matrixfederationclient.py +1874 -0
  391. synapse/http/proxy.py +290 -0
  392. synapse/http/proxyagent.py +497 -0
  393. synapse/http/replicationagent.py +203 -0
  394. synapse/http/request_metrics.py +309 -0
  395. synapse/http/server.py +1111 -0
  396. synapse/http/servlet.py +1018 -0
  397. synapse/http/site.py +952 -0
  398. synapse/http/types.py +27 -0
  399. synapse/logging/__init__.py +31 -0
  400. synapse/logging/_remote.py +261 -0
  401. synapse/logging/_terse_json.py +95 -0
  402. synapse/logging/context.py +1209 -0
  403. synapse/logging/formatter.py +62 -0
  404. synapse/logging/handlers.py +99 -0
  405. synapse/logging/loggers.py +25 -0
  406. synapse/logging/opentracing.py +1132 -0
  407. synapse/logging/scopecontextmanager.py +160 -0
  408. synapse/media/_base.py +831 -0
  409. synapse/media/filepath.py +417 -0
  410. synapse/media/media_repository.py +1595 -0
  411. synapse/media/media_storage.py +703 -0
  412. synapse/media/oembed.py +277 -0
  413. synapse/media/preview_html.py +556 -0
  414. synapse/media/storage_provider.py +195 -0
  415. synapse/media/thumbnailer.py +833 -0
  416. synapse/media/url_previewer.py +884 -0
  417. synapse/metrics/__init__.py +748 -0
  418. synapse/metrics/_gc.py +219 -0
  419. synapse/metrics/_reactor_metrics.py +171 -0
  420. synapse/metrics/_types.py +38 -0
  421. synapse/metrics/background_process_metrics.py +555 -0
  422. synapse/metrics/common_usage_metrics.py +95 -0
  423. synapse/metrics/jemalloc.py +248 -0
  424. synapse/module_api/__init__.py +2131 -0
  425. synapse/module_api/callbacks/__init__.py +50 -0
  426. synapse/module_api/callbacks/account_validity_callbacks.py +106 -0
  427. synapse/module_api/callbacks/media_repository_callbacks.py +157 -0
  428. synapse/module_api/callbacks/ratelimit_callbacks.py +78 -0
  429. synapse/module_api/callbacks/spamchecker_callbacks.py +991 -0
  430. synapse/module_api/callbacks/third_party_event_rules_callbacks.py +592 -0
  431. synapse/module_api/errors.py +42 -0
  432. synapse/notifier.py +969 -0
  433. synapse/push/__init__.py +212 -0
  434. synapse/push/bulk_push_rule_evaluator.py +635 -0
  435. synapse/push/clientformat.py +126 -0
  436. synapse/push/emailpusher.py +334 -0
  437. synapse/push/httppusher.py +565 -0
  438. synapse/push/mailer.py +1009 -0
  439. synapse/push/presentable_names.py +216 -0
  440. synapse/push/push_tools.py +114 -0
  441. synapse/push/push_types.py +141 -0
  442. synapse/push/pusher.py +87 -0
  443. synapse/push/pusherpool.py +501 -0
  444. synapse/push/rulekinds.py +33 -0
  445. synapse/py.typed +0 -0
  446. synapse/replication/__init__.py +20 -0
  447. synapse/replication/http/__init__.py +68 -0
  448. synapse/replication/http/_base.py +469 -0
  449. synapse/replication/http/account_data.py +297 -0
  450. synapse/replication/http/deactivate_account.py +81 -0
  451. synapse/replication/http/delayed_events.py +62 -0
  452. synapse/replication/http/devices.py +254 -0
  453. synapse/replication/http/federation.py +334 -0
  454. synapse/replication/http/login.py +106 -0
  455. synapse/replication/http/membership.py +364 -0
  456. synapse/replication/http/presence.py +133 -0
  457. synapse/replication/http/push.py +156 -0
  458. synapse/replication/http/register.py +172 -0
  459. synapse/replication/http/send_events.py +182 -0
  460. synapse/replication/http/state.py +82 -0
  461. synapse/replication/http/streams.py +101 -0
  462. synapse/replication/tcp/__init__.py +56 -0
  463. synapse/replication/tcp/client.py +553 -0
  464. synapse/replication/tcp/commands.py +569 -0
  465. synapse/replication/tcp/context.py +41 -0
  466. synapse/replication/tcp/external_cache.py +156 -0
  467. synapse/replication/tcp/handler.py +922 -0
  468. synapse/replication/tcp/protocol.py +611 -0
  469. synapse/replication/tcp/redis.py +510 -0
  470. synapse/replication/tcp/resource.py +349 -0
  471. synapse/replication/tcp/streams/__init__.py +96 -0
  472. synapse/replication/tcp/streams/_base.py +765 -0
  473. synapse/replication/tcp/streams/events.py +287 -0
  474. synapse/replication/tcp/streams/federation.py +92 -0
  475. synapse/replication/tcp/streams/partial_state.py +80 -0
  476. synapse/res/providers.json +29 -0
  477. synapse/res/templates/_base.html +29 -0
  478. synapse/res/templates/account_previously_renewed.html +6 -0
  479. synapse/res/templates/account_renewed.html +6 -0
  480. synapse/res/templates/add_threepid.html +8 -0
  481. synapse/res/templates/add_threepid.txt +6 -0
  482. synapse/res/templates/add_threepid_failure.html +7 -0
  483. synapse/res/templates/add_threepid_success.html +6 -0
  484. synapse/res/templates/already_in_use.html +12 -0
  485. synapse/res/templates/already_in_use.txt +10 -0
  486. synapse/res/templates/auth_success.html +21 -0
  487. synapse/res/templates/invalid_token.html +6 -0
  488. synapse/res/templates/mail-Element.css +7 -0
  489. synapse/res/templates/mail-Vector.css +7 -0
  490. synapse/res/templates/mail-expiry.css +4 -0
  491. synapse/res/templates/mail.css +156 -0
  492. synapse/res/templates/notice_expiry.html +46 -0
  493. synapse/res/templates/notice_expiry.txt +7 -0
  494. synapse/res/templates/notif.html +51 -0
  495. synapse/res/templates/notif.txt +22 -0
  496. synapse/res/templates/notif_mail.html +59 -0
  497. synapse/res/templates/notif_mail.txt +10 -0
  498. synapse/res/templates/password_reset.html +10 -0
  499. synapse/res/templates/password_reset.txt +7 -0
  500. synapse/res/templates/password_reset_confirmation.html +15 -0
  501. synapse/res/templates/password_reset_failure.html +7 -0
  502. synapse/res/templates/password_reset_success.html +6 -0
  503. synapse/res/templates/recaptcha.html +42 -0
  504. synapse/res/templates/registration.html +12 -0
  505. synapse/res/templates/registration.txt +10 -0
  506. synapse/res/templates/registration_failure.html +6 -0
  507. synapse/res/templates/registration_success.html +6 -0
  508. synapse/res/templates/registration_token.html +18 -0
  509. synapse/res/templates/room.html +33 -0
  510. synapse/res/templates/room.txt +9 -0
  511. synapse/res/templates/sso.css +129 -0
  512. synapse/res/templates/sso_account_deactivated.html +25 -0
  513. synapse/res/templates/sso_auth_account_details.html +186 -0
  514. synapse/res/templates/sso_auth_account_details.js +116 -0
  515. synapse/res/templates/sso_auth_bad_user.html +26 -0
  516. synapse/res/templates/sso_auth_confirm.html +27 -0
  517. synapse/res/templates/sso_auth_success.html +26 -0
  518. synapse/res/templates/sso_error.html +71 -0
  519. synapse/res/templates/sso_footer.html +19 -0
  520. synapse/res/templates/sso_login_idp_picker.html +60 -0
  521. synapse/res/templates/sso_new_user_consent.html +30 -0
  522. synapse/res/templates/sso_partial_profile.html +19 -0
  523. synapse/res/templates/sso_redirect_confirm.html +39 -0
  524. synapse/res/templates/style.css +33 -0
  525. synapse/res/templates/terms.html +27 -0
  526. synapse/rest/__init__.py +197 -0
  527. synapse/rest/admin/__init__.py +395 -0
  528. synapse/rest/admin/_base.py +72 -0
  529. synapse/rest/admin/background_updates.py +171 -0
  530. synapse/rest/admin/devices.py +221 -0
  531. synapse/rest/admin/event_reports.py +173 -0
  532. synapse/rest/admin/events.py +69 -0
  533. synapse/rest/admin/experimental_features.py +137 -0
  534. synapse/rest/admin/federation.py +243 -0
  535. synapse/rest/admin/media.py +540 -0
  536. synapse/rest/admin/registration_tokens.py +358 -0
  537. synapse/rest/admin/rooms.py +1092 -0
  538. synapse/rest/admin/scheduled_tasks.py +70 -0
  539. synapse/rest/admin/server_notice_servlet.py +132 -0
  540. synapse/rest/admin/statistics.py +132 -0
  541. synapse/rest/admin/username_available.py +58 -0
  542. synapse/rest/admin/users.py +1634 -0
  543. synapse/rest/client/__init__.py +20 -0
  544. synapse/rest/client/_base.py +113 -0
  545. synapse/rest/client/account.py +937 -0
  546. synapse/rest/client/account_data.py +319 -0
  547. synapse/rest/client/account_validity.py +103 -0
  548. synapse/rest/client/appservice_ping.py +125 -0
  549. synapse/rest/client/auth.py +218 -0
  550. synapse/rest/client/auth_metadata.py +122 -0
  551. synapse/rest/client/capabilities.py +121 -0
  552. synapse/rest/client/delayed_events.py +165 -0
  553. synapse/rest/client/devices.py +587 -0
  554. synapse/rest/client/directory.py +211 -0
  555. synapse/rest/client/events.py +116 -0
  556. synapse/rest/client/filter.py +112 -0
  557. synapse/rest/client/initial_sync.py +65 -0
  558. synapse/rest/client/keys.py +678 -0
  559. synapse/rest/client/knock.py +104 -0
  560. synapse/rest/client/login.py +750 -0
  561. synapse/rest/client/login_token_request.py +127 -0
  562. synapse/rest/client/logout.py +93 -0
  563. synapse/rest/client/matrixrtc.py +52 -0
  564. synapse/rest/client/media.py +307 -0
  565. synapse/rest/client/mutual_rooms.py +145 -0
  566. synapse/rest/client/notifications.py +137 -0
  567. synapse/rest/client/openid.py +109 -0
  568. synapse/rest/client/password_policy.py +69 -0
  569. synapse/rest/client/presence.py +131 -0
  570. synapse/rest/client/profile.py +291 -0
  571. synapse/rest/client/push_rule.py +331 -0
  572. synapse/rest/client/pusher.py +181 -0
  573. synapse/rest/client/read_marker.py +104 -0
  574. synapse/rest/client/receipts.py +165 -0
  575. synapse/rest/client/register.py +1072 -0
  576. synapse/rest/client/relations.py +138 -0
  577. synapse/rest/client/rendezvous.py +76 -0
  578. synapse/rest/client/reporting.py +207 -0
  579. synapse/rest/client/room.py +1763 -0
  580. synapse/rest/client/room_keys.py +426 -0
  581. synapse/rest/client/room_upgrade_rest_servlet.py +112 -0
  582. synapse/rest/client/sendtodevice.py +85 -0
  583. synapse/rest/client/sync.py +1131 -0
  584. synapse/rest/client/tags.py +129 -0
  585. synapse/rest/client/thirdparty.py +130 -0
  586. synapse/rest/client/thread_subscriptions.py +247 -0
  587. synapse/rest/client/tokenrefresh.py +52 -0
  588. synapse/rest/client/transactions.py +150 -0
  589. synapse/rest/client/user_directory.py +99 -0
  590. synapse/rest/client/versions.py +193 -0
  591. synapse/rest/client/voip.py +88 -0
  592. synapse/rest/consent/__init__.py +0 -0
  593. synapse/rest/consent/consent_resource.py +210 -0
  594. synapse/rest/health.py +38 -0
  595. synapse/rest/key/__init__.py +20 -0
  596. synapse/rest/key/v2/__init__.py +40 -0
  597. synapse/rest/key/v2/local_key_resource.py +125 -0
  598. synapse/rest/key/v2/remote_key_resource.py +302 -0
  599. synapse/rest/media/__init__.py +0 -0
  600. synapse/rest/media/config_resource.py +53 -0
  601. synapse/rest/media/create_resource.py +90 -0
  602. synapse/rest/media/download_resource.py +110 -0
  603. synapse/rest/media/media_repository_resource.py +113 -0
  604. synapse/rest/media/preview_url_resource.py +77 -0
  605. synapse/rest/media/thumbnail_resource.py +142 -0
  606. synapse/rest/media/upload_resource.py +187 -0
  607. synapse/rest/media/v1/__init__.py +39 -0
  608. synapse/rest/media/v1/_base.py +23 -0
  609. synapse/rest/media/v1/media_storage.py +23 -0
  610. synapse/rest/media/v1/storage_provider.py +23 -0
  611. synapse/rest/synapse/__init__.py +20 -0
  612. synapse/rest/synapse/client/__init__.py +93 -0
  613. synapse/rest/synapse/client/federation_whitelist.py +66 -0
  614. synapse/rest/synapse/client/jwks.py +77 -0
  615. synapse/rest/synapse/client/new_user_consent.py +115 -0
  616. synapse/rest/synapse/client/oidc/__init__.py +45 -0
  617. synapse/rest/synapse/client/oidc/backchannel_logout_resource.py +42 -0
  618. synapse/rest/synapse/client/oidc/callback_resource.py +48 -0
  619. synapse/rest/synapse/client/password_reset.py +129 -0
  620. synapse/rest/synapse/client/pick_idp.py +107 -0
  621. synapse/rest/synapse/client/pick_username.py +153 -0
  622. synapse/rest/synapse/client/rendezvous.py +58 -0
  623. synapse/rest/synapse/client/saml2/__init__.py +42 -0
  624. synapse/rest/synapse/client/saml2/metadata_resource.py +46 -0
  625. synapse/rest/synapse/client/saml2/response_resource.py +52 -0
  626. synapse/rest/synapse/client/sso_register.py +56 -0
  627. synapse/rest/synapse/client/unsubscribe.py +88 -0
  628. synapse/rest/synapse/mas/__init__.py +71 -0
  629. synapse/rest/synapse/mas/_base.py +55 -0
  630. synapse/rest/synapse/mas/devices.py +239 -0
  631. synapse/rest/synapse/mas/users.py +469 -0
  632. synapse/rest/well_known.py +148 -0
  633. synapse/server.py +1279 -0
  634. synapse/server_notices/__init__.py +0 -0
  635. synapse/server_notices/consent_server_notices.py +136 -0
  636. synapse/server_notices/resource_limits_server_notices.py +215 -0
  637. synapse/server_notices/server_notices_manager.py +388 -0
  638. synapse/server_notices/server_notices_sender.py +67 -0
  639. synapse/server_notices/worker_server_notices_sender.py +46 -0
  640. synapse/spam_checker_api/__init__.py +31 -0
  641. synapse/state/__init__.py +1023 -0
  642. synapse/state/v1.py +369 -0
  643. synapse/state/v2.py +985 -0
  644. synapse/static/client/login/index.html +47 -0
  645. synapse/static/client/login/js/jquery-3.4.1.min.js +2 -0
  646. synapse/static/client/login/js/login.js +291 -0
  647. synapse/static/client/login/spinner.gif +0 -0
  648. synapse/static/client/login/style.css +79 -0
  649. synapse/static/index.html +63 -0
  650. synapse/storage/__init__.py +43 -0
  651. synapse/storage/_base.py +245 -0
  652. synapse/storage/admin_client_config.py +25 -0
  653. synapse/storage/background_updates.py +1189 -0
  654. synapse/storage/controllers/__init__.py +57 -0
  655. synapse/storage/controllers/persist_events.py +1237 -0
  656. synapse/storage/controllers/purge_events.py +456 -0
  657. synapse/storage/controllers/state.py +950 -0
  658. synapse/storage/controllers/stats.py +119 -0
  659. synapse/storage/database.py +2720 -0
  660. synapse/storage/databases/__init__.py +175 -0
  661. synapse/storage/databases/main/__init__.py +420 -0
  662. synapse/storage/databases/main/account_data.py +1073 -0
  663. synapse/storage/databases/main/appservice.py +473 -0
  664. synapse/storage/databases/main/cache.py +912 -0
  665. synapse/storage/databases/main/censor_events.py +226 -0
  666. synapse/storage/databases/main/client_ips.py +816 -0
  667. synapse/storage/databases/main/delayed_events.py +577 -0
  668. synapse/storage/databases/main/deviceinbox.py +1272 -0
  669. synapse/storage/databases/main/devices.py +2579 -0
  670. synapse/storage/databases/main/directory.py +212 -0
  671. synapse/storage/databases/main/e2e_room_keys.py +689 -0
  672. synapse/storage/databases/main/end_to_end_keys.py +1894 -0
  673. synapse/storage/databases/main/event_federation.py +2511 -0
  674. synapse/storage/databases/main/event_push_actions.py +1936 -0
  675. synapse/storage/databases/main/events.py +3765 -0
  676. synapse/storage/databases/main/events_bg_updates.py +2910 -0
  677. synapse/storage/databases/main/events_forward_extremities.py +126 -0
  678. synapse/storage/databases/main/events_worker.py +2787 -0
  679. synapse/storage/databases/main/experimental_features.py +130 -0
  680. synapse/storage/databases/main/filtering.py +231 -0
  681. synapse/storage/databases/main/keys.py +291 -0
  682. synapse/storage/databases/main/lock.py +554 -0
  683. synapse/storage/databases/main/media_repository.py +1068 -0
  684. synapse/storage/databases/main/metrics.py +461 -0
  685. synapse/storage/databases/main/monthly_active_users.py +443 -0
  686. synapse/storage/databases/main/openid.py +60 -0
  687. synapse/storage/databases/main/presence.py +509 -0
  688. synapse/storage/databases/main/profile.py +539 -0
  689. synapse/storage/databases/main/purge_events.py +521 -0
  690. synapse/storage/databases/main/push_rule.py +970 -0
  691. synapse/storage/databases/main/pusher.py +793 -0
  692. synapse/storage/databases/main/receipts.py +1341 -0
  693. synapse/storage/databases/main/registration.py +3071 -0
  694. synapse/storage/databases/main/rejections.py +37 -0
  695. synapse/storage/databases/main/relations.py +1116 -0
  696. synapse/storage/databases/main/room.py +2779 -0
  697. synapse/storage/databases/main/roommember.py +2132 -0
  698. synapse/storage/databases/main/search.py +939 -0
  699. synapse/storage/databases/main/session.py +152 -0
  700. synapse/storage/databases/main/signatures.py +94 -0
  701. synapse/storage/databases/main/sliding_sync.py +842 -0
  702. synapse/storage/databases/main/state.py +1002 -0
  703. synapse/storage/databases/main/state_deltas.py +360 -0
  704. synapse/storage/databases/main/stats.py +789 -0
  705. synapse/storage/databases/main/stream.py +2589 -0
  706. synapse/storage/databases/main/tags.py +360 -0
  707. synapse/storage/databases/main/task_scheduler.py +225 -0
  708. synapse/storage/databases/main/thread_subscriptions.py +589 -0
  709. synapse/storage/databases/main/transactions.py +676 -0
  710. synapse/storage/databases/main/ui_auth.py +420 -0
  711. synapse/storage/databases/main/user_directory.py +1330 -0
  712. synapse/storage/databases/main/user_erasure_store.py +117 -0
  713. synapse/storage/databases/state/__init__.py +22 -0
  714. synapse/storage/databases/state/bg_updates.py +497 -0
  715. synapse/storage/databases/state/deletion.py +557 -0
  716. synapse/storage/databases/state/store.py +948 -0
  717. synapse/storage/engines/__init__.py +70 -0
  718. synapse/storage/engines/_base.py +154 -0
  719. synapse/storage/engines/postgres.py +261 -0
  720. synapse/storage/engines/sqlite.py +199 -0
  721. synapse/storage/invite_rule.py +152 -0
  722. synapse/storage/keys.py +40 -0
  723. synapse/storage/prepare_database.py +730 -0
  724. synapse/storage/push_rule.py +28 -0
  725. synapse/storage/roommember.py +88 -0
  726. synapse/storage/schema/README.md +4 -0
  727. synapse/storage/schema/__init__.py +186 -0
  728. synapse/storage/schema/common/delta/25/00background_updates.sql +40 -0
  729. synapse/storage/schema/common/delta/35/00background_updates_add_col.sql +36 -0
  730. synapse/storage/schema/common/delta/58/00background_update_ordering.sql +38 -0
  731. synapse/storage/schema/common/full_schemas/72/full.sql.postgres +8 -0
  732. synapse/storage/schema/common/full_schemas/72/full.sql.sqlite +6 -0
  733. synapse/storage/schema/common/schema_version.sql +60 -0
  734. synapse/storage/schema/main/delta/12/v12.sql +82 -0
  735. synapse/storage/schema/main/delta/13/v13.sql +38 -0
  736. synapse/storage/schema/main/delta/14/v14.sql +42 -0
  737. synapse/storage/schema/main/delta/15/appservice_txns.sql +50 -0
  738. synapse/storage/schema/main/delta/15/presence_indices.sql +2 -0
  739. synapse/storage/schema/main/delta/15/v15.sql +24 -0
  740. synapse/storage/schema/main/delta/16/events_order_index.sql +4 -0
  741. synapse/storage/schema/main/delta/16/remote_media_cache_index.sql +2 -0
  742. synapse/storage/schema/main/delta/16/remove_duplicates.sql +9 -0
  743. synapse/storage/schema/main/delta/16/room_alias_index.sql +3 -0
  744. synapse/storage/schema/main/delta/16/unique_constraints.sql +72 -0
  745. synapse/storage/schema/main/delta/16/users.sql +56 -0
  746. synapse/storage/schema/main/delta/17/drop_indexes.sql +37 -0
  747. synapse/storage/schema/main/delta/17/server_keys.sql +43 -0
  748. synapse/storage/schema/main/delta/17/user_threepids.sql +9 -0
  749. synapse/storage/schema/main/delta/18/server_keys_bigger_ints.sql +51 -0
  750. synapse/storage/schema/main/delta/19/event_index.sql +38 -0
  751. synapse/storage/schema/main/delta/20/dummy.sql +1 -0
  752. synapse/storage/schema/main/delta/20/pushers.py +93 -0
  753. synapse/storage/schema/main/delta/21/end_to_end_keys.sql +53 -0
  754. synapse/storage/schema/main/delta/21/receipts.sql +57 -0
  755. synapse/storage/schema/main/delta/22/receipts_index.sql +41 -0
  756. synapse/storage/schema/main/delta/22/user_threepids_unique.sql +19 -0
  757. synapse/storage/schema/main/delta/24/stats_reporting.sql +37 -0
  758. synapse/storage/schema/main/delta/25/fts.py +81 -0
  759. synapse/storage/schema/main/delta/25/guest_access.sql +44 -0
  760. synapse/storage/schema/main/delta/25/history_visibility.sql +44 -0
  761. synapse/storage/schema/main/delta/25/tags.sql +57 -0
  762. synapse/storage/schema/main/delta/26/account_data.sql +36 -0
  763. synapse/storage/schema/main/delta/27/account_data.sql +55 -0
  764. synapse/storage/schema/main/delta/27/forgotten_memberships.sql +45 -0
  765. synapse/storage/schema/main/delta/27/ts.py +61 -0
  766. synapse/storage/schema/main/delta/28/event_push_actions.sql +46 -0
  767. synapse/storage/schema/main/delta/28/events_room_stream.sql +39 -0
  768. synapse/storage/schema/main/delta/28/public_roms_index.sql +39 -0
  769. synapse/storage/schema/main/delta/28/receipts_user_id_index.sql +41 -0
  770. synapse/storage/schema/main/delta/28/upgrade_times.sql +40 -0
  771. synapse/storage/schema/main/delta/28/users_is_guest.sql +41 -0
  772. synapse/storage/schema/main/delta/29/push_actions.sql +54 -0
  773. synapse/storage/schema/main/delta/30/alias_creator.sql +35 -0
  774. synapse/storage/schema/main/delta/30/as_users.py +82 -0
  775. synapse/storage/schema/main/delta/30/deleted_pushers.sql +44 -0
  776. synapse/storage/schema/main/delta/30/presence_stream.sql +49 -0
  777. synapse/storage/schema/main/delta/30/public_rooms.sql +42 -0
  778. synapse/storage/schema/main/delta/30/push_rule_stream.sql +57 -0
  779. synapse/storage/schema/main/delta/30/threepid_guest_access_tokens.sql +43 -0
  780. synapse/storage/schema/main/delta/31/invites.sql +61 -0
  781. synapse/storage/schema/main/delta/31/local_media_repository_url_cache.sql +46 -0
  782. synapse/storage/schema/main/delta/31/pushers_0.py +92 -0
  783. synapse/storage/schema/main/delta/31/pushers_index.sql +41 -0
  784. synapse/storage/schema/main/delta/31/search_update.py +65 -0
  785. synapse/storage/schema/main/delta/32/events.sql +35 -0
  786. synapse/storage/schema/main/delta/32/openid.sql +9 -0
  787. synapse/storage/schema/main/delta/32/pusher_throttle.sql +42 -0
  788. synapse/storage/schema/main/delta/32/remove_indices.sql +52 -0
  789. synapse/storage/schema/main/delta/32/reports.sql +44 -0
  790. synapse/storage/schema/main/delta/33/access_tokens_device_index.sql +36 -0
  791. synapse/storage/schema/main/delta/33/devices.sql +40 -0
  792. synapse/storage/schema/main/delta/33/devices_for_e2e_keys.sql +38 -0
  793. synapse/storage/schema/main/delta/33/devices_for_e2e_keys_clear_unknown_device.sql +39 -0
  794. synapse/storage/schema/main/delta/33/event_fields.py +61 -0
  795. synapse/storage/schema/main/delta/33/remote_media_ts.py +43 -0
  796. synapse/storage/schema/main/delta/33/user_ips_index.sql +36 -0
  797. synapse/storage/schema/main/delta/34/appservice_stream.sql +42 -0
  798. synapse/storage/schema/main/delta/34/cache_stream.py +50 -0
  799. synapse/storage/schema/main/delta/34/device_inbox.sql +43 -0
  800. synapse/storage/schema/main/delta/34/push_display_name_rename.sql +39 -0
  801. synapse/storage/schema/main/delta/34/received_txn_purge.py +36 -0
  802. synapse/storage/schema/main/delta/35/contains_url.sql +36 -0
  803. synapse/storage/schema/main/delta/35/device_outbox.sql +58 -0
  804. synapse/storage/schema/main/delta/35/device_stream_id.sql +40 -0
  805. synapse/storage/schema/main/delta/35/event_push_actions_index.sql +36 -0
  806. synapse/storage/schema/main/delta/35/public_room_list_change_stream.sql +52 -0
  807. synapse/storage/schema/main/delta/35/stream_order_to_extrem.sql +56 -0
  808. synapse/storage/schema/main/delta/36/readd_public_rooms.sql +45 -0
  809. synapse/storage/schema/main/delta/37/remove_auth_idx.py +89 -0
  810. synapse/storage/schema/main/delta/37/user_threepids.sql +71 -0
  811. synapse/storage/schema/main/delta/38/postgres_fts_gist.sql +38 -0
  812. synapse/storage/schema/main/delta/39/appservice_room_list.sql +48 -0
  813. synapse/storage/schema/main/delta/39/device_federation_stream_idx.sql +35 -0
  814. synapse/storage/schema/main/delta/39/event_push_index.sql +36 -0
  815. synapse/storage/schema/main/delta/39/federation_out_position.sql +41 -0
  816. synapse/storage/schema/main/delta/39/membership_profile.sql +39 -0
  817. synapse/storage/schema/main/delta/40/current_state_idx.sql +36 -0
  818. synapse/storage/schema/main/delta/40/device_inbox.sql +40 -0
  819. synapse/storage/schema/main/delta/40/device_list_streams.sql +79 -0
  820. synapse/storage/schema/main/delta/40/event_push_summary.sql +57 -0
  821. synapse/storage/schema/main/delta/40/pushers.sql +58 -0
  822. synapse/storage/schema/main/delta/41/device_list_stream_idx.sql +36 -0
  823. synapse/storage/schema/main/delta/41/device_outbound_index.sql +35 -0
  824. synapse/storage/schema/main/delta/41/event_search_event_id_idx.sql +36 -0
  825. synapse/storage/schema/main/delta/41/ratelimit.sql +41 -0
  826. synapse/storage/schema/main/delta/42/current_state_delta.sql +48 -0
  827. synapse/storage/schema/main/delta/42/device_list_last_id.sql +52 -0
  828. synapse/storage/schema/main/delta/42/event_auth_state_only.sql +36 -0
  829. synapse/storage/schema/main/delta/42/user_dir.py +88 -0
  830. synapse/storage/schema/main/delta/43/blocked_rooms.sql +40 -0
  831. synapse/storage/schema/main/delta/43/quarantine_media.sql +36 -0
  832. synapse/storage/schema/main/delta/43/url_cache.sql +35 -0
  833. synapse/storage/schema/main/delta/43/user_share.sql +52 -0
  834. synapse/storage/schema/main/delta/44/expire_url_cache.sql +60 -0
  835. synapse/storage/schema/main/delta/45/group_server.sql +186 -0
  836. synapse/storage/schema/main/delta/45/profile_cache.sql +47 -0
  837. synapse/storage/schema/main/delta/46/drop_refresh_tokens.sql +36 -0
  838. synapse/storage/schema/main/delta/46/drop_unique_deleted_pushers.sql +54 -0
  839. synapse/storage/schema/main/delta/46/group_server.sql +51 -0
  840. synapse/storage/schema/main/delta/46/local_media_repository_url_idx.sql +43 -0
  841. synapse/storage/schema/main/delta/46/user_dir_null_room_ids.sql +54 -0
  842. synapse/storage/schema/main/delta/46/user_dir_typos.sql +43 -0
  843. synapse/storage/schema/main/delta/47/last_access_media.sql +35 -0
  844. synapse/storage/schema/main/delta/47/postgres_fts_gin.sql +36 -0
  845. synapse/storage/schema/main/delta/47/push_actions_staging.sql +47 -0
  846. synapse/storage/schema/main/delta/48/add_user_consent.sql +37 -0
  847. synapse/storage/schema/main/delta/48/add_user_ips_last_seen_index.sql +36 -0
  848. synapse/storage/schema/main/delta/48/deactivated_users.sql +44 -0
  849. synapse/storage/schema/main/delta/48/group_unique_indexes.py +67 -0
  850. synapse/storage/schema/main/delta/48/groups_joinable.sql +41 -0
  851. synapse/storage/schema/main/delta/49/add_user_consent_server_notice_sent.sql +39 -0
  852. synapse/storage/schema/main/delta/49/add_user_daily_visits.sql +40 -0
  853. synapse/storage/schema/main/delta/49/add_user_ips_last_seen_only_index.sql +36 -0
  854. synapse/storage/schema/main/delta/50/add_creation_ts_users_index.sql +38 -0
  855. synapse/storage/schema/main/delta/50/erasure_store.sql +40 -0
  856. synapse/storage/schema/main/delta/50/make_event_content_nullable.py +102 -0
  857. synapse/storage/schema/main/delta/51/e2e_room_keys.sql +58 -0
  858. synapse/storage/schema/main/delta/51/monthly_active_users.sql +46 -0
  859. synapse/storage/schema/main/delta/52/add_event_to_state_group_index.sql +38 -0
  860. synapse/storage/schema/main/delta/52/device_list_streams_unique_idx.sql +55 -0
  861. synapse/storage/schema/main/delta/52/e2e_room_keys.sql +72 -0
  862. synapse/storage/schema/main/delta/53/add_user_type_to_users.sql +38 -0
  863. synapse/storage/schema/main/delta/53/drop_sent_transactions.sql +35 -0
  864. synapse/storage/schema/main/delta/53/event_format_version.sql +35 -0
  865. synapse/storage/schema/main/delta/53/user_dir_populate.sql +49 -0
  866. synapse/storage/schema/main/delta/53/user_ips_index.sql +49 -0
  867. synapse/storage/schema/main/delta/53/user_share.sql +63 -0
  868. synapse/storage/schema/main/delta/53/user_threepid_id.sql +48 -0
  869. synapse/storage/schema/main/delta/53/users_in_public_rooms.sql +47 -0
  870. synapse/storage/schema/main/delta/54/account_validity_with_renewal.sql +49 -0
  871. synapse/storage/schema/main/delta/54/add_validity_to_server_keys.sql +42 -0
  872. synapse/storage/schema/main/delta/54/delete_forward_extremities.sql +42 -0
  873. synapse/storage/schema/main/delta/54/drop_legacy_tables.sql +49 -0
  874. synapse/storage/schema/main/delta/54/drop_presence_list.sql +35 -0
  875. synapse/storage/schema/main/delta/54/relations.sql +46 -0
  876. synapse/storage/schema/main/delta/54/stats.sql +99 -0
  877. synapse/storage/schema/main/delta/54/stats2.sql +47 -0
  878. synapse/storage/schema/main/delta/55/access_token_expiry.sql +37 -0
  879. synapse/storage/schema/main/delta/55/track_threepid_validations.sql +50 -0
  880. synapse/storage/schema/main/delta/55/users_alter_deactivated.sql +38 -0
  881. synapse/storage/schema/main/delta/56/add_spans_to_device_lists.sql +39 -0
  882. synapse/storage/schema/main/delta/56/current_state_events_membership.sql +41 -0
  883. synapse/storage/schema/main/delta/56/current_state_events_membership_mk2.sql +43 -0
  884. synapse/storage/schema/main/delta/56/delete_keys_from_deleted_backups.sql +44 -0
  885. synapse/storage/schema/main/delta/56/destinations_failure_ts.sql +44 -0
  886. synapse/storage/schema/main/delta/56/destinations_retry_interval_type.sql.postgres +18 -0
  887. synapse/storage/schema/main/delta/56/device_stream_id_insert.sql +39 -0
  888. synapse/storage/schema/main/delta/56/devices_last_seen.sql +43 -0
  889. synapse/storage/schema/main/delta/56/drop_unused_event_tables.sql +39 -0
  890. synapse/storage/schema/main/delta/56/event_expiry.sql +40 -0
  891. synapse/storage/schema/main/delta/56/event_labels.sql +49 -0
  892. synapse/storage/schema/main/delta/56/event_labels_background_update.sql +36 -0
  893. synapse/storage/schema/main/delta/56/fix_room_keys_index.sql +37 -0
  894. synapse/storage/schema/main/delta/56/hidden_devices.sql +37 -0
  895. synapse/storage/schema/main/delta/56/hidden_devices_fix.sql.sqlite +42 -0
  896. synapse/storage/schema/main/delta/56/nuke_empty_communities_from_db.sql +48 -0
  897. synapse/storage/schema/main/delta/56/public_room_list_idx.sql +35 -0
  898. synapse/storage/schema/main/delta/56/redaction_censor.sql +35 -0
  899. synapse/storage/schema/main/delta/56/redaction_censor2.sql +41 -0
  900. synapse/storage/schema/main/delta/56/redaction_censor3_fix_update.sql.postgres +25 -0
  901. synapse/storage/schema/main/delta/56/redaction_censor4.sql +35 -0
  902. synapse/storage/schema/main/delta/56/remove_tombstoned_rooms_from_directory.sql +38 -0
  903. synapse/storage/schema/main/delta/56/room_key_etag.sql +36 -0
  904. synapse/storage/schema/main/delta/56/room_membership_idx.sql +37 -0
  905. synapse/storage/schema/main/delta/56/room_retention.sql +52 -0
  906. synapse/storage/schema/main/delta/56/signing_keys.sql +75 -0
  907. synapse/storage/schema/main/delta/56/signing_keys_nonunique_signatures.sql +41 -0
  908. synapse/storage/schema/main/delta/56/stats_separated.sql +175 -0
  909. synapse/storage/schema/main/delta/56/unique_user_filter_index.py +46 -0
  910. synapse/storage/schema/main/delta/56/user_external_ids.sql +43 -0
  911. synapse/storage/schema/main/delta/56/users_in_public_rooms_idx.sql +36 -0
  912. synapse/storage/schema/main/delta/57/delete_old_current_state_events.sql +41 -0
  913. synapse/storage/schema/main/delta/57/device_list_remote_cache_stale.sql +44 -0
  914. synapse/storage/schema/main/delta/57/local_current_membership.py +111 -0
  915. synapse/storage/schema/main/delta/57/remove_sent_outbound_pokes.sql +40 -0
  916. synapse/storage/schema/main/delta/57/rooms_version_column.sql +43 -0
  917. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.postgres +35 -0
  918. synapse/storage/schema/main/delta/57/rooms_version_column_2.sql.sqlite +22 -0
  919. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.postgres +39 -0
  920. synapse/storage/schema/main/delta/57/rooms_version_column_3.sql.sqlite +23 -0
  921. synapse/storage/schema/main/delta/58/02remove_dup_outbound_pokes.sql +41 -0
  922. synapse/storage/schema/main/delta/58/03persist_ui_auth.sql +55 -0
  923. synapse/storage/schema/main/delta/58/05cache_instance.sql.postgres +30 -0
  924. synapse/storage/schema/main/delta/58/06dlols_unique_idx.py +83 -0
  925. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.postgres +33 -0
  926. synapse/storage/schema/main/delta/58/07add_method_to_thumbnail_constraint.sql.sqlite +44 -0
  927. synapse/storage/schema/main/delta/58/07persist_ui_auth_ips.sql +44 -0
  928. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.postgres +18 -0
  929. synapse/storage/schema/main/delta/58/08_media_safe_from_quarantine.sql.sqlite +18 -0
  930. synapse/storage/schema/main/delta/58/09shadow_ban.sql +37 -0
  931. synapse/storage/schema/main/delta/58/10_pushrules_enabled_delete_obsolete.sql +47 -0
  932. synapse/storage/schema/main/delta/58/10drop_local_rejections_stream.sql +41 -0
  933. synapse/storage/schema/main/delta/58/10federation_pos_instance_name.sql +41 -0
  934. synapse/storage/schema/main/delta/58/11dehydration.sql +39 -0
  935. synapse/storage/schema/main/delta/58/11fallback.sql +43 -0
  936. synapse/storage/schema/main/delta/58/11user_id_seq.py +38 -0
  937. synapse/storage/schema/main/delta/58/12room_stats.sql +51 -0
  938. synapse/storage/schema/main/delta/58/13remove_presence_allow_inbound.sql +36 -0
  939. synapse/storage/schema/main/delta/58/14events_instance_name.sql +35 -0
  940. synapse/storage/schema/main/delta/58/14events_instance_name.sql.postgres +28 -0
  941. synapse/storage/schema/main/delta/58/15_catchup_destination_rooms.sql +61 -0
  942. synapse/storage/schema/main/delta/58/15unread_count.sql +45 -0
  943. synapse/storage/schema/main/delta/58/16populate_stats_process_rooms_fix.sql +41 -0
  944. synapse/storage/schema/main/delta/58/17_catchup_last_successful.sql +40 -0
  945. synapse/storage/schema/main/delta/58/18stream_positions.sql +41 -0
  946. synapse/storage/schema/main/delta/58/19instance_map.sql.postgres +25 -0
  947. synapse/storage/schema/main/delta/58/19txn_id.sql +59 -0
  948. synapse/storage/schema/main/delta/58/20instance_name_event_tables.sql +36 -0
  949. synapse/storage/schema/main/delta/58/20user_daily_visits.sql +37 -0
  950. synapse/storage/schema/main/delta/58/21as_device_stream.sql +36 -0
  951. synapse/storage/schema/main/delta/58/21drop_device_max_stream_id.sql +1 -0
  952. synapse/storage/schema/main/delta/58/22puppet_token.sql +36 -0
  953. synapse/storage/schema/main/delta/58/22users_have_local_media.sql +2 -0
  954. synapse/storage/schema/main/delta/58/23e2e_cross_signing_keys_idx.sql +36 -0
  955. synapse/storage/schema/main/delta/58/24drop_event_json_index.sql +38 -0
  956. synapse/storage/schema/main/delta/58/25user_external_ids_user_id_idx.sql +36 -0
  957. synapse/storage/schema/main/delta/58/26access_token_last_validated.sql +37 -0
  958. synapse/storage/schema/main/delta/58/27local_invites.sql +37 -0
  959. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.postgres +16 -0
  960. synapse/storage/schema/main/delta/58/28drop_last_used_column.sql.sqlite +62 -0
  961. synapse/storage/schema/main/delta/59/01ignored_user.py +85 -0
  962. synapse/storage/schema/main/delta/59/02shard_send_to_device.sql +37 -0
  963. synapse/storage/schema/main/delta/59/03shard_send_to_device_sequence.sql.postgres +25 -0
  964. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql +71 -0
  965. synapse/storage/schema/main/delta/59/04_event_auth_chains.sql.postgres +16 -0
  966. synapse/storage/schema/main/delta/59/04drop_account_data.sql +36 -0
  967. synapse/storage/schema/main/delta/59/05cache_invalidation.sql +36 -0
  968. synapse/storage/schema/main/delta/59/06chain_cover_index.sql +36 -0
  969. synapse/storage/schema/main/delta/59/06shard_account_data.sql +39 -0
  970. synapse/storage/schema/main/delta/59/06shard_account_data.sql.postgres +32 -0
  971. synapse/storage/schema/main/delta/59/07shard_account_data_fix.sql +37 -0
  972. synapse/storage/schema/main/delta/59/08delete_pushers_for_deactivated_accounts.sql +39 -0
  973. synapse/storage/schema/main/delta/59/08delete_stale_pushers.sql +39 -0
  974. synapse/storage/schema/main/delta/59/09rejected_events_metadata.sql +45 -0
  975. synapse/storage/schema/main/delta/59/10delete_purged_chain_cover.sql +36 -0
  976. synapse/storage/schema/main/delta/59/11add_knock_members_to_stats.sql +39 -0
  977. synapse/storage/schema/main/delta/59/11drop_thumbnail_constraint.sql.postgres +22 -0
  978. synapse/storage/schema/main/delta/59/12account_validity_token_used_ts_ms.sql +37 -0
  979. synapse/storage/schema/main/delta/59/12presence_stream_instance.sql +37 -0
  980. synapse/storage/schema/main/delta/59/12presence_stream_instance_seq.sql.postgres +20 -0
  981. synapse/storage/schema/main/delta/59/13users_to_send_full_presence_to.sql +53 -0
  982. synapse/storage/schema/main/delta/59/14refresh_tokens.sql +53 -0
  983. synapse/storage/schema/main/delta/59/15locks.sql +56 -0
  984. synapse/storage/schema/main/delta/59/16federation_inbound_staging.sql +51 -0
  985. synapse/storage/schema/main/delta/60/01recreate_stream_ordering.sql.postgres +45 -0
  986. synapse/storage/schema/main/delta/60/02change_stream_ordering_columns.sql.postgres +30 -0
  987. synapse/storage/schema/main/delta/61/01change_appservices_txns.sql.postgres +23 -0
  988. synapse/storage/schema/main/delta/61/01insertion_event_lookups.sql +68 -0
  989. synapse/storage/schema/main/delta/61/02drop_redundant_room_depth_index.sql +37 -0
  990. synapse/storage/schema/main/delta/61/03recreate_min_depth.py +74 -0
  991. synapse/storage/schema/main/delta/62/01insertion_event_extremities.sql +43 -0
  992. synapse/storage/schema/main/delta/63/01create_registration_tokens.sql +42 -0
  993. synapse/storage/schema/main/delta/63/02delete_unlinked_email_pushers.sql +39 -0
  994. synapse/storage/schema/main/delta/63/02populate-rooms-creator.sql +36 -0
  995. synapse/storage/schema/main/delta/63/03session_store.sql +42 -0
  996. synapse/storage/schema/main/delta/63/04add_presence_stream_not_offline_index.sql +37 -0
  997. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.postgres +23 -0
  998. synapse/storage/schema/main/delta/64/01msc2716_chunk_to_batch_rename.sql.sqlite +37 -0
  999. synapse/storage/schema/main/delta/65/01msc2716_insertion_event_edges.sql +38 -0
  1000. synapse/storage/schema/main/delta/65/03remove_hidden_devices_from_device_inbox.sql +41 -0
  1001. synapse/storage/schema/main/delta/65/04_local_group_updates.sql +37 -0
  1002. synapse/storage/schema/main/delta/65/05_remove_room_stats_historical_and_user_stats_historical.sql +38 -0
  1003. synapse/storage/schema/main/delta/65/06remove_deleted_devices_from_device_inbox.sql +53 -0
  1004. synapse/storage/schema/main/delta/65/07_arbitrary_relations.sql +37 -0
  1005. synapse/storage/schema/main/delta/65/08_device_inbox_background_updates.sql +37 -0
  1006. synapse/storage/schema/main/delta/65/10_expirable_refresh_tokens.sql +47 -0
  1007. synapse/storage/schema/main/delta/65/11_devices_auth_provider_session.sql +46 -0
  1008. synapse/storage/schema/main/delta/67/01drop_public_room_list_stream.sql +37 -0
  1009. synapse/storage/schema/main/delta/68/01event_columns.sql +45 -0
  1010. synapse/storage/schema/main/delta/68/02_msc2409_add_device_id_appservice_stream_type.sql +40 -0
  1011. synapse/storage/schema/main/delta/68/03_delete_account_data_for_deactivated_accounts.sql +39 -0
  1012. synapse/storage/schema/main/delta/68/04_refresh_tokens_index_next_token_id.sql +47 -0
  1013. synapse/storage/schema/main/delta/68/04partial_state_rooms.sql +60 -0
  1014. synapse/storage/schema/main/delta/68/05_delete_non_strings_from_event_search.sql.sqlite +22 -0
  1015. synapse/storage/schema/main/delta/68/05partial_state_rooms_triggers.py +80 -0
  1016. synapse/storage/schema/main/delta/68/06_msc3202_add_device_list_appservice_stream_type.sql +42 -0
  1017. synapse/storage/schema/main/delta/69/01as_txn_seq.py +54 -0
  1018. synapse/storage/schema/main/delta/69/01device_list_oubound_by_room.sql +57 -0
  1019. synapse/storage/schema/main/delta/69/02cache_invalidation_index.sql +37 -0
  1020. synapse/storage/schema/main/delta/70/01clean_table_purged_rooms.sql +39 -0
  1021. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.postgres +43 -0
  1022. synapse/storage/schema/main/delta/71/01rebuild_event_edges.sql.sqlite +47 -0
  1023. synapse/storage/schema/main/delta/71/01remove_noop_background_updates.sql +80 -0
  1024. synapse/storage/schema/main/delta/71/02event_push_summary_unique.sql +37 -0
  1025. synapse/storage/schema/main/delta/72/01add_room_type_to_state_stats.sql +38 -0
  1026. synapse/storage/schema/main/delta/72/01event_push_summary_receipt.sql +54 -0
  1027. synapse/storage/schema/main/delta/72/02event_push_actions_index.sql +38 -0
  1028. synapse/storage/schema/main/delta/72/03bg_populate_events_columns.py +57 -0
  1029. synapse/storage/schema/main/delta/72/03drop_event_reference_hashes.sql +36 -0
  1030. synapse/storage/schema/main/delta/72/03remove_groups.sql +50 -0
  1031. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.postgres +17 -0
  1032. synapse/storage/schema/main/delta/72/04drop_column_application_services_state_last_txn.sql.sqlite +40 -0
  1033. synapse/storage/schema/main/delta/72/05receipts_event_stream_ordering.sql +38 -0
  1034. synapse/storage/schema/main/delta/72/05remove_unstable_private_read_receipts.sql +38 -0
  1035. synapse/storage/schema/main/delta/72/06add_consent_ts_to_users.sql +35 -0
  1036. synapse/storage/schema/main/delta/72/06thread_notifications.sql +49 -0
  1037. synapse/storage/schema/main/delta/72/07force_update_current_state_events_membership.py +67 -0
  1038. synapse/storage/schema/main/delta/72/07thread_receipts.sql.postgres +30 -0
  1039. synapse/storage/schema/main/delta/72/07thread_receipts.sql.sqlite +70 -0
  1040. synapse/storage/schema/main/delta/72/08begin_cache_invalidation_seq_at_2.sql.postgres +23 -0
  1041. synapse/storage/schema/main/delta/72/08thread_receipts.sql +39 -0
  1042. synapse/storage/schema/main/delta/72/09partial_indices.sql.sqlite +56 -0
  1043. synapse/storage/schema/main/delta/73/01event_failed_pull_attempts.sql +48 -0
  1044. synapse/storage/schema/main/delta/73/02add_pusher_enabled.sql +35 -0
  1045. synapse/storage/schema/main/delta/73/02room_id_indexes_for_purging.sql +41 -0
  1046. synapse/storage/schema/main/delta/73/03pusher_device_id.sql +39 -0
  1047. synapse/storage/schema/main/delta/73/03users_approved_column.sql +39 -0
  1048. synapse/storage/schema/main/delta/73/04partial_join_details.sql +42 -0
  1049. synapse/storage/schema/main/delta/73/04pending_device_list_updates.sql +47 -0
  1050. synapse/storage/schema/main/delta/73/05old_push_actions.sql.postgres +22 -0
  1051. synapse/storage/schema/main/delta/73/05old_push_actions.sql.sqlite +24 -0
  1052. synapse/storage/schema/main/delta/73/06thread_notifications_thread_id_idx.sql +42 -0
  1053. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.postgres +23 -0
  1054. synapse/storage/schema/main/delta/73/08thread_receipts_non_null.sql.sqlite +76 -0
  1055. synapse/storage/schema/main/delta/73/09partial_joined_via_destination.sql +37 -0
  1056. synapse/storage/schema/main/delta/73/09threads_table.sql +49 -0
  1057. synapse/storage/schema/main/delta/73/10_update_sqlite_fts4_tokenizer.py +71 -0
  1058. synapse/storage/schema/main/delta/73/10login_tokens.sql +54 -0
  1059. synapse/storage/schema/main/delta/73/11event_search_room_id_n_distinct.sql.postgres +33 -0
  1060. synapse/storage/schema/main/delta/73/12refactor_device_list_outbound_pokes.sql +72 -0
  1061. synapse/storage/schema/main/delta/73/13add_device_lists_index.sql +39 -0
  1062. synapse/storage/schema/main/delta/73/20_un_partial_stated_room_stream.sql +51 -0
  1063. synapse/storage/schema/main/delta/73/21_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  1064. synapse/storage/schema/main/delta/73/22_rebuild_user_dir_stats.sql +48 -0
  1065. synapse/storage/schema/main/delta/73/22_un_partial_stated_event_stream.sql +53 -0
  1066. synapse/storage/schema/main/delta/73/23_fix_thread_index.sql +52 -0
  1067. synapse/storage/schema/main/delta/73/23_un_partial_stated_room_stream_seq.sql.postgres +20 -0
  1068. synapse/storage/schema/main/delta/73/24_events_jump_to_date_index.sql +36 -0
  1069. synapse/storage/schema/main/delta/73/25drop_presence.sql +36 -0
  1070. synapse/storage/schema/main/delta/74/01_user_directory_stale_remote_users.sql +58 -0
  1071. synapse/storage/schema/main/delta/74/02_set_device_id_for_pushers_bg_update.sql +38 -0
  1072. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.postgres +29 -0
  1073. synapse/storage/schema/main/delta/74/03_membership_tables_event_stream_ordering.sql.sqlite +23 -0
  1074. synapse/storage/schema/main/delta/74/03_room_membership_index.sql +38 -0
  1075. synapse/storage/schema/main/delta/74/04_delete_e2e_backup_keys_for_deactivated_users.sql +36 -0
  1076. synapse/storage/schema/main/delta/74/04_membership_tables_event_stream_ordering_triggers.py +87 -0
  1077. synapse/storage/schema/main/delta/74/05_events_txn_id_device_id.sql +72 -0
  1078. synapse/storage/schema/main/delta/74/90COMMENTS_destinations.sql.postgres +52 -0
  1079. synapse/storage/schema/main/delta/76/01_add_profiles_full_user_id_column.sql +39 -0
  1080. synapse/storage/schema/main/delta/76/02_add_user_filters_full_user_id_column.sql +39 -0
  1081. synapse/storage/schema/main/delta/76/03_per_user_experimental_features.sql +46 -0
  1082. synapse/storage/schema/main/delta/76/04_add_room_forgetter.sql +43 -0
  1083. synapse/storage/schema/main/delta/77/01_add_profiles_not_valid_check.sql.postgres +16 -0
  1084. synapse/storage/schema/main/delta/77/02_add_user_filters_not_valid_check.sql.postgres +16 -0
  1085. synapse/storage/schema/main/delta/77/03bg_populate_full_user_id_profiles.sql +35 -0
  1086. synapse/storage/schema/main/delta/77/04bg_populate_full_user_id_user_filters.sql +35 -0
  1087. synapse/storage/schema/main/delta/77/05thread_notifications_backfill.sql +67 -0
  1088. synapse/storage/schema/main/delta/77/06thread_notifications_not_null.sql.sqlite +102 -0
  1089. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions.sql.postgres +27 -0
  1090. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_actions_staging.sql.postgres +27 -0
  1091. synapse/storage/schema/main/delta/77/06thread_notifications_not_null_event_push_summary.sql.postgres +29 -0
  1092. synapse/storage/schema/main/delta/77/14bg_indices_event_stream_ordering.sql +39 -0
  1093. synapse/storage/schema/main/delta/78/01_validate_and_update_profiles.py +99 -0
  1094. synapse/storage/schema/main/delta/78/02_validate_and_update_user_filters.py +100 -0
  1095. synapse/storage/schema/main/delta/78/03_remove_unused_indexes_user_filters.py +72 -0
  1096. synapse/storage/schema/main/delta/78/03event_extremities_constraints.py +65 -0
  1097. synapse/storage/schema/main/delta/78/04_add_full_user_id_index_user_filters.py +32 -0
  1098. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.postgres +102 -0
  1099. synapse/storage/schema/main/delta/79/03_read_write_locks_triggers.sql.sqlite +72 -0
  1100. synapse/storage/schema/main/delta/79/04_mitigate_stream_ordering_update_race.py +70 -0
  1101. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.postgres +69 -0
  1102. synapse/storage/schema/main/delta/79/05_read_write_locks_triggers.sql.sqlite +65 -0
  1103. synapse/storage/schema/main/delta/80/01_users_alter_locked.sql +35 -0
  1104. synapse/storage/schema/main/delta/80/02_read_write_locks_unlogged.sql.postgres +30 -0
  1105. synapse/storage/schema/main/delta/80/02_scheduled_tasks.sql +47 -0
  1106. synapse/storage/schema/main/delta/80/03_read_write_locks_triggers.sql.postgres +37 -0
  1107. synapse/storage/schema/main/delta/80/04_read_write_locks_deadlock.sql.postgres +71 -0
  1108. synapse/storage/schema/main/delta/82/02_scheduled_tasks_index.sql +35 -0
  1109. synapse/storage/schema/main/delta/82/04_add_indices_for_purging_rooms.sql +39 -0
  1110. synapse/storage/schema/main/delta/82/05gaps.sql +44 -0
  1111. synapse/storage/schema/main/delta/83/01_drop_old_tables.sql +43 -0
  1112. synapse/storage/schema/main/delta/83/03_instance_name_receipts.sql.sqlite +17 -0
  1113. synapse/storage/schema/main/delta/83/05_cross_signing_key_update_grant.sql +34 -0
  1114. synapse/storage/schema/main/delta/83/06_event_push_summary_room.sql +36 -0
  1115. synapse/storage/schema/main/delta/84/01_auth_links_stats.sql.postgres +20 -0
  1116. synapse/storage/schema/main/delta/84/02_auth_links_index.sql +16 -0
  1117. synapse/storage/schema/main/delta/84/03_auth_links_analyze.sql.postgres +16 -0
  1118. synapse/storage/schema/main/delta/84/04_access_token_index.sql +15 -0
  1119. synapse/storage/schema/main/delta/85/01_add_suspended.sql +14 -0
  1120. synapse/storage/schema/main/delta/85/02_add_instance_names.sql +27 -0
  1121. synapse/storage/schema/main/delta/85/03_new_sequences.sql.postgres +54 -0
  1122. synapse/storage/schema/main/delta/85/04_cleanup_device_federation_outbox.sql +15 -0
  1123. synapse/storage/schema/main/delta/85/05_add_instance_names_converted_pos.sql +16 -0
  1124. synapse/storage/schema/main/delta/85/06_add_room_reports.sql +20 -0
  1125. synapse/storage/schema/main/delta/86/01_authenticate_media.sql +15 -0
  1126. synapse/storage/schema/main/delta/86/02_receipts_event_id_index.sql +15 -0
  1127. synapse/storage/schema/main/delta/87/01_sliding_sync_memberships.sql +169 -0
  1128. synapse/storage/schema/main/delta/87/02_per_connection_state.sql +81 -0
  1129. synapse/storage/schema/main/delta/87/03_current_state_index.sql +19 -0
  1130. synapse/storage/schema/main/delta/88/01_add_delayed_events.sql +43 -0
  1131. synapse/storage/schema/main/delta/88/01_custom_profile_fields.sql +15 -0
  1132. synapse/storage/schema/main/delta/88/02_fix_sliding_sync_membership_snapshots_forgotten_column.sql +21 -0
  1133. synapse/storage/schema/main/delta/88/03_add_otk_ts_added_index.sql +18 -0
  1134. synapse/storage/schema/main/delta/88/04_current_state_delta_index.sql +18 -0
  1135. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.postgres +19 -0
  1136. synapse/storage/schema/main/delta/88/05_drop_old_otks.sql.sqlite +19 -0
  1137. synapse/storage/schema/main/delta/88/05_sliding_sync_room_config_index.sql +20 -0
  1138. synapse/storage/schema/main/delta/88/06_events_received_ts_index.sql +17 -0
  1139. synapse/storage/schema/main/delta/89/01_sliding_sync_membership_snapshot_index.sql +15 -0
  1140. synapse/storage/schema/main/delta/90/01_add_column_participant_room_memberships_table.sql +16 -0
  1141. synapse/storage/schema/main/delta/91/01_media_hash.sql +28 -0
  1142. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.postgres +16 -0
  1143. synapse/storage/schema/main/delta/92/01_remove_trigger.sql.sqlite +16 -0
  1144. synapse/storage/schema/main/delta/92/02_remove_populate_participant_bg_update.sql +17 -0
  1145. synapse/storage/schema/main/delta/92/04_ss_membership_snapshot_idx.sql +16 -0
  1146. synapse/storage/schema/main/delta/92/04_thread_subscriptions.sql +59 -0
  1147. synapse/storage/schema/main/delta/92/04_thread_subscriptions_seq.sql.postgres +19 -0
  1148. synapse/storage/schema/main/delta/92/05_fixup_max_depth_cap.sql +17 -0
  1149. synapse/storage/schema/main/delta/92/05_thread_subscriptions_comments.sql.postgres +18 -0
  1150. synapse/storage/schema/main/delta/92/06_device_federation_inbox_index.sql +16 -0
  1151. synapse/storage/schema/main/delta/92/06_threads_last_sent_stream_ordering_comments.sql.postgres +24 -0
  1152. synapse/storage/schema/main/delta/92/07_add_user_reports.sql +22 -0
  1153. synapse/storage/schema/main/delta/92/07_event_txn_id_device_id_txn_id2.sql +15 -0
  1154. synapse/storage/schema/main/delta/92/08_room_ban_redactions.sql +21 -0
  1155. synapse/storage/schema/main/delta/92/08_thread_subscriptions_seq_fixup.sql.postgres +19 -0
  1156. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql +20 -0
  1157. synapse/storage/schema/main/delta/92/09_thread_subscriptions_update.sql.postgres +18 -0
  1158. synapse/storage/schema/main/delta/93/01_add_delayed_events.sql +15 -0
  1159. synapse/storage/schema/main/delta/93/02_sliding_sync_members.sql +60 -0
  1160. synapse/storage/schema/main/delta/93/03_sss_pos_last_used.sql +27 -0
  1161. synapse/storage/schema/main/full_schemas/72/full.sql.postgres +1344 -0
  1162. synapse/storage/schema/main/full_schemas/72/full.sql.sqlite +646 -0
  1163. synapse/storage/schema/state/delta/23/drop_state_index.sql +35 -0
  1164. synapse/storage/schema/state/delta/32/remove_state_indices.sql +38 -0
  1165. synapse/storage/schema/state/delta/35/add_state_index.sql +36 -0
  1166. synapse/storage/schema/state/delta/35/state.sql +41 -0
  1167. synapse/storage/schema/state/delta/35/state_dedupe.sql +36 -0
  1168. synapse/storage/schema/state/delta/47/state_group_seq.py +38 -0
  1169. synapse/storage/schema/state/delta/56/state_group_room_idx.sql +36 -0
  1170. synapse/storage/schema/state/delta/61/02state_groups_state_n_distinct.sql.postgres +34 -0
  1171. synapse/storage/schema/state/delta/70/08_state_group_edges_unique.sql +36 -0
  1172. synapse/storage/schema/state/delta/89/01_state_groups_deletion.sql +39 -0
  1173. synapse/storage/schema/state/delta/90/02_delete_unreferenced_state_groups.sql +16 -0
  1174. synapse/storage/schema/state/delta/90/03_remove_old_deletion_bg_update.sql +15 -0
  1175. synapse/storage/schema/state/full_schemas/72/full.sql.postgres +30 -0
  1176. synapse/storage/schema/state/full_schemas/72/full.sql.sqlite +20 -0
  1177. synapse/storage/types.py +183 -0
  1178. synapse/storage/util/__init__.py +20 -0
  1179. synapse/storage/util/id_generators.py +928 -0
  1180. synapse/storage/util/partial_state_events_tracker.py +194 -0
  1181. synapse/storage/util/sequence.py +315 -0
  1182. synapse/streams/__init__.py +43 -0
  1183. synapse/streams/config.py +91 -0
  1184. synapse/streams/events.py +203 -0
  1185. synapse/synapse_rust/__init__.pyi +3 -0
  1186. synapse/synapse_rust/acl.pyi +20 -0
  1187. synapse/synapse_rust/events.pyi +136 -0
  1188. synapse/synapse_rust/http_client.pyi +32 -0
  1189. synapse/synapse_rust/push.pyi +86 -0
  1190. synapse/synapse_rust/rendezvous.pyi +30 -0
  1191. synapse/synapse_rust/segmenter.pyi +1 -0
  1192. synapse/synapse_rust.abi3.so +0 -0
  1193. synapse/types/__init__.py +1600 -0
  1194. synapse/types/handlers/__init__.py +93 -0
  1195. synapse/types/handlers/policy_server.py +16 -0
  1196. synapse/types/handlers/sliding_sync.py +1004 -0
  1197. synapse/types/rest/__init__.py +25 -0
  1198. synapse/types/rest/client/__init__.py +413 -0
  1199. synapse/types/state.py +634 -0
  1200. synapse/types/storage/__init__.py +66 -0
  1201. synapse/util/__init__.py +160 -0
  1202. synapse/util/async_helpers.py +1048 -0
  1203. synapse/util/background_queue.py +142 -0
  1204. synapse/util/batching_queue.py +203 -0
  1205. synapse/util/caches/__init__.py +300 -0
  1206. synapse/util/caches/cached_call.py +143 -0
  1207. synapse/util/caches/deferred_cache.py +530 -0
  1208. synapse/util/caches/descriptors.py +692 -0
  1209. synapse/util/caches/dictionary_cache.py +346 -0
  1210. synapse/util/caches/expiringcache.py +250 -0
  1211. synapse/util/caches/lrucache.py +976 -0
  1212. synapse/util/caches/response_cache.py +323 -0
  1213. synapse/util/caches/stream_change_cache.py +370 -0
  1214. synapse/util/caches/treecache.py +189 -0
  1215. synapse/util/caches/ttlcache.py +197 -0
  1216. synapse/util/cancellation.py +63 -0
  1217. synapse/util/check_dependencies.py +335 -0
  1218. synapse/util/clock.py +592 -0
  1219. synapse/util/daemonize.py +165 -0
  1220. synapse/util/distributor.py +157 -0
  1221. synapse/util/duration.py +117 -0
  1222. synapse/util/events.py +134 -0
  1223. synapse/util/file_consumer.py +164 -0
  1224. synapse/util/frozenutils.py +57 -0
  1225. synapse/util/gai_resolver.py +178 -0
  1226. synapse/util/hash.py +38 -0
  1227. synapse/util/httpresourcetree.py +108 -0
  1228. synapse/util/iterutils.py +190 -0
  1229. synapse/util/json.py +56 -0
  1230. synapse/util/linked_list.py +156 -0
  1231. synapse/util/logcontext.py +46 -0
  1232. synapse/util/logformatter.py +28 -0
  1233. synapse/util/macaroons.py +325 -0
  1234. synapse/util/manhole.py +191 -0
  1235. synapse/util/metrics.py +339 -0
  1236. synapse/util/module_loader.py +116 -0
  1237. synapse/util/msisdn.py +51 -0
  1238. synapse/util/patch_inline_callbacks.py +250 -0
  1239. synapse/util/pydantic_models.py +63 -0
  1240. synapse/util/ratelimitutils.py +422 -0
  1241. synapse/util/retryutils.py +339 -0
  1242. synapse/util/rlimit.py +42 -0
  1243. synapse/util/rust.py +164 -0
  1244. synapse/util/sentinel.py +21 -0
  1245. synapse/util/stringutils.py +293 -0
  1246. synapse/util/task_scheduler.py +494 -0
  1247. synapse/util/templates.py +126 -0
  1248. synapse/util/threepids.py +123 -0
  1249. synapse/util/wheel_timer.py +112 -0
  1250. synapse/visibility.py +869 -0
  1251. synmark/__init__.py +47 -0
  1252. synmark/__main__.py +128 -0
  1253. synmark/suites/__init__.py +9 -0
  1254. synmark/suites/logging.py +154 -0
  1255. synmark/suites/lrucache.py +48 -0
  1256. synmark/suites/lrucache_evict.py +49 -0
  1257. sytest-blacklist +33 -0
  1258. tests/__init__.py +29 -0
  1259. tests/api/__init__.py +0 -0
  1260. tests/api/test_auth.py +548 -0
  1261. tests/api/test_errors.py +46 -0
  1262. tests/api/test_filtering.py +622 -0
  1263. tests/api/test_ratelimiting.py +505 -0
  1264. tests/api/test_urls.py +81 -0
  1265. tests/app/__init__.py +0 -0
  1266. tests/app/test_homeserver_shutdown.py +271 -0
  1267. tests/app/test_homeserver_start.py +49 -0
  1268. tests/app/test_openid_listener.py +139 -0
  1269. tests/app/test_phone_stats_home.py +248 -0
  1270. tests/appservice/__init__.py +20 -0
  1271. tests/appservice/test_api.py +253 -0
  1272. tests/appservice/test_appservice.py +259 -0
  1273. tests/appservice/test_scheduler.py +477 -0
  1274. tests/config/__init__.py +20 -0
  1275. tests/config/test___main__.py +38 -0
  1276. tests/config/test_api.py +146 -0
  1277. tests/config/test_appservice.py +48 -0
  1278. tests/config/test_background_update.py +65 -0
  1279. tests/config/test_base.py +151 -0
  1280. tests/config/test_cache.py +193 -0
  1281. tests/config/test_database.py +42 -0
  1282. tests/config/test_generate.py +72 -0
  1283. tests/config/test_load.py +322 -0
  1284. tests/config/test_oauth_delegation.py +454 -0
  1285. tests/config/test_ratelimiting.py +77 -0
  1286. tests/config/test_registration_config.py +203 -0
  1287. tests/config/test_room_directory.py +203 -0
  1288. tests/config/test_server.py +248 -0
  1289. tests/config/test_tls.py +209 -0
  1290. tests/config/test_util.py +59 -0
  1291. tests/config/test_workers.py +332 -0
  1292. tests/config/utils.py +66 -0
  1293. tests/crypto/__init__.py +20 -0
  1294. tests/crypto/test_event_signing.py +109 -0
  1295. tests/crypto/test_keyring.py +737 -0
  1296. tests/events/__init__.py +0 -0
  1297. tests/events/test_auto_accept_invites.py +827 -0
  1298. tests/events/test_presence_router.py +540 -0
  1299. tests/events/test_snapshot.py +121 -0
  1300. tests/events/test_utils.py +986 -0
  1301. tests/federation/__init__.py +0 -0
  1302. tests/federation/test_complexity.py +257 -0
  1303. tests/federation/test_federation_catch_up.py +585 -0
  1304. tests/federation/test_federation_client.py +316 -0
  1305. tests/federation/test_federation_devices.py +161 -0
  1306. tests/federation/test_federation_media.py +295 -0
  1307. tests/federation/test_federation_out_of_band_membership.py +671 -0
  1308. tests/federation/test_federation_sender.py +956 -0
  1309. tests/federation/test_federation_server.py +631 -0
  1310. tests/federation/transport/__init__.py +0 -0
  1311. tests/federation/transport/server/__init__.py +20 -0
  1312. tests/federation/transport/server/test__base.py +156 -0
  1313. tests/federation/transport/test_client.py +157 -0
  1314. tests/federation/transport/test_knocking.py +323 -0
  1315. tests/federation/transport/test_server.py +74 -0
  1316. tests/handlers/__init__.py +0 -0
  1317. tests/handlers/oidc_test_key.p8 +5 -0
  1318. tests/handlers/oidc_test_key.pub.pem +4 -0
  1319. tests/handlers/test_admin.py +361 -0
  1320. tests/handlers/test_appservice.py +1336 -0
  1321. tests/handlers/test_auth.py +248 -0
  1322. tests/handlers/test_cas.py +239 -0
  1323. tests/handlers/test_deactivate_account.py +485 -0
  1324. tests/handlers/test_device.py +665 -0
  1325. tests/handlers/test_directory.py +613 -0
  1326. tests/handlers/test_e2e_keys.py +2025 -0
  1327. tests/handlers/test_e2e_room_keys.py +569 -0
  1328. tests/handlers/test_federation.py +794 -0
  1329. tests/handlers/test_federation_event.py +1181 -0
  1330. tests/handlers/test_message.py +322 -0
  1331. tests/handlers/test_oauth_delegation.py +1314 -0
  1332. tests/handlers/test_oidc.py +1688 -0
  1333. tests/handlers/test_password_providers.py +987 -0
  1334. tests/handlers/test_presence.py +2144 -0
  1335. tests/handlers/test_profile.py +401 -0
  1336. tests/handlers/test_receipts.py +342 -0
  1337. tests/handlers/test_register.py +880 -0
  1338. tests/handlers/test_room.py +108 -0
  1339. tests/handlers/test_room_list.py +93 -0
  1340. tests/handlers/test_room_member.py +764 -0
  1341. tests/handlers/test_room_policy.py +468 -0
  1342. tests/handlers/test_room_summary.py +1248 -0
  1343. tests/handlers/test_saml.py +427 -0
  1344. tests/handlers/test_send_email.py +230 -0
  1345. tests/handlers/test_sliding_sync.py +5065 -0
  1346. tests/handlers/test_sso.py +152 -0
  1347. tests/handlers/test_stats.py +594 -0
  1348. tests/handlers/test_sync.py +1275 -0
  1349. tests/handlers/test_typing.py +557 -0
  1350. tests/handlers/test_user_directory.py +1435 -0
  1351. tests/handlers/test_worker_lock.py +126 -0
  1352. tests/http/__init__.py +196 -0
  1353. tests/http/ca.crt +19 -0
  1354. tests/http/ca.key +27 -0
  1355. tests/http/federation/__init__.py +19 -0
  1356. tests/http/federation/test_matrix_federation_agent.py +1855 -0
  1357. tests/http/federation/test_srv_resolver.py +220 -0
  1358. tests/http/server/__init__.py +20 -0
  1359. tests/http/server/_base.py +621 -0
  1360. tests/http/server.key +27 -0
  1361. tests/http/test_additional_resource.py +76 -0
  1362. tests/http/test_client.py +422 -0
  1363. tests/http/test_endpoint.py +62 -0
  1364. tests/http/test_matrixfederationclient.py +1092 -0
  1365. tests/http/test_proxy.py +75 -0
  1366. tests/http/test_proxyagent.py +1008 -0
  1367. tests/http/test_servlet.py +145 -0
  1368. tests/http/test_simple_client.py +188 -0
  1369. tests/http/test_site.py +247 -0
  1370. tests/logging/__init__.py +42 -0
  1371. tests/logging/test_loggers.py +127 -0
  1372. tests/logging/test_opentracing.py +524 -0
  1373. tests/logging/test_remote_handler.py +184 -0
  1374. tests/logging/test_terse_json.py +253 -0
  1375. tests/media/__init__.py +20 -0
  1376. tests/media/test_base.py +88 -0
  1377. tests/media/test_filepath.py +602 -0
  1378. tests/media/test_html_preview.py +565 -0
  1379. tests/media/test_media_retention.py +299 -0
  1380. tests/media/test_media_storage.py +1401 -0
  1381. tests/media/test_oembed.py +172 -0
  1382. tests/media/test_url_previewer.py +120 -0
  1383. tests/metrics/__init__.py +0 -0
  1384. tests/metrics/test_background_process_metrics.py +21 -0
  1385. tests/metrics/test_metrics.py +407 -0
  1386. tests/metrics/test_phone_home_stats.py +263 -0
  1387. tests/module_api/__init__.py +0 -0
  1388. tests/module_api/test_account_data_manager.py +171 -0
  1389. tests/module_api/test_api.py +1035 -0
  1390. tests/module_api/test_event_unsigned_addition.py +66 -0
  1391. tests/module_api/test_spamchecker.py +286 -0
  1392. tests/push/__init__.py +0 -0
  1393. tests/push/test_bulk_push_rule_evaluator.py +652 -0
  1394. tests/push/test_email.py +570 -0
  1395. tests/push/test_http.py +1247 -0
  1396. tests/push/test_presentable_names.py +238 -0
  1397. tests/push/test_push_rule_evaluator.py +1069 -0
  1398. tests/replication/__init__.py +20 -0
  1399. tests/replication/_base.py +619 -0
  1400. tests/replication/http/__init__.py +20 -0
  1401. tests/replication/http/test__base.py +113 -0
  1402. tests/replication/storage/__init__.py +20 -0
  1403. tests/replication/storage/_base.py +85 -0
  1404. tests/replication/storage/test_events.py +299 -0
  1405. tests/replication/tcp/__init__.py +19 -0
  1406. tests/replication/tcp/streams/__init__.py +19 -0
  1407. tests/replication/tcp/streams/test_account_data.py +133 -0
  1408. tests/replication/tcp/streams/test_events.py +565 -0
  1409. tests/replication/tcp/streams/test_federation.py +117 -0
  1410. tests/replication/tcp/streams/test_partial_state.py +72 -0
  1411. tests/replication/tcp/streams/test_receipts.py +110 -0
  1412. tests/replication/tcp/streams/test_thread_subscriptions.py +157 -0
  1413. tests/replication/tcp/streams/test_to_device.py +112 -0
  1414. tests/replication/tcp/streams/test_typing.py +223 -0
  1415. tests/replication/tcp/test_commands.py +50 -0
  1416. tests/replication/tcp/test_handler.py +211 -0
  1417. tests/replication/test_auth.py +120 -0
  1418. tests/replication/test_client_reader_shard.py +101 -0
  1419. tests/replication/test_federation_ack.py +88 -0
  1420. tests/replication/test_federation_sender_shard.py +352 -0
  1421. tests/replication/test_module_cache_invalidation.py +89 -0
  1422. tests/replication/test_multi_media_repo.py +496 -0
  1423. tests/replication/test_pusher_shard.py +192 -0
  1424. tests/replication/test_sharded_event_persister.py +332 -0
  1425. tests/replication/test_sharded_receipts.py +250 -0
  1426. tests/rest/__init__.py +20 -0
  1427. tests/rest/admin/__init__.py +19 -0
  1428. tests/rest/admin/test_admin.py +614 -0
  1429. tests/rest/admin/test_background_updates.py +375 -0
  1430. tests/rest/admin/test_device.py +600 -0
  1431. tests/rest/admin/test_event.py +74 -0
  1432. tests/rest/admin/test_event_reports.py +781 -0
  1433. tests/rest/admin/test_federation.py +863 -0
  1434. tests/rest/admin/test_jwks.py +106 -0
  1435. tests/rest/admin/test_media.py +1091 -0
  1436. tests/rest/admin/test_registration_tokens.py +729 -0
  1437. tests/rest/admin/test_room.py +3626 -0
  1438. tests/rest/admin/test_scheduled_tasks.py +192 -0
  1439. tests/rest/admin/test_server_notice.py +753 -0
  1440. tests/rest/admin/test_statistics.py +523 -0
  1441. tests/rest/admin/test_user.py +6061 -0
  1442. tests/rest/admin/test_username_available.py +82 -0
  1443. tests/rest/client/__init__.py +20 -0
  1444. tests/rest/client/sliding_sync/__init__.py +13 -0
  1445. tests/rest/client/sliding_sync/test_connection_tracking.py +505 -0
  1446. tests/rest/client/sliding_sync/test_extension_account_data.py +1056 -0
  1447. tests/rest/client/sliding_sync/test_extension_e2ee.py +459 -0
  1448. tests/rest/client/sliding_sync/test_extension_receipts.py +934 -0
  1449. tests/rest/client/sliding_sync/test_extension_thread_subscriptions.py +497 -0
  1450. tests/rest/client/sliding_sync/test_extension_to_device.py +294 -0
  1451. tests/rest/client/sliding_sync/test_extension_typing.py +500 -0
  1452. tests/rest/client/sliding_sync/test_extensions.py +306 -0
  1453. tests/rest/client/sliding_sync/test_lists_filters.py +1975 -0
  1454. tests/rest/client/sliding_sync/test_room_subscriptions.py +303 -0
  1455. tests/rest/client/sliding_sync/test_rooms_invites.py +528 -0
  1456. tests/rest/client/sliding_sync/test_rooms_meta.py +1338 -0
  1457. tests/rest/client/sliding_sync/test_rooms_required_state.py +2247 -0
  1458. tests/rest/client/sliding_sync/test_rooms_timeline.py +718 -0
  1459. tests/rest/client/sliding_sync/test_sliding_sync.py +1688 -0
  1460. tests/rest/client/test_account.py +1543 -0
  1461. tests/rest/client/test_account_data.py +81 -0
  1462. tests/rest/client/test_auth.py +1508 -0
  1463. tests/rest/client/test_auth_metadata.py +145 -0
  1464. tests/rest/client/test_capabilities.py +318 -0
  1465. tests/rest/client/test_consent.py +138 -0
  1466. tests/rest/client/test_delayed_events.py +553 -0
  1467. tests/rest/client/test_devices.py +634 -0
  1468. tests/rest/client/test_directory.py +249 -0
  1469. tests/rest/client/test_ephemeral_message.py +113 -0
  1470. tests/rest/client/test_events.py +165 -0
  1471. tests/rest/client/test_filter.py +124 -0
  1472. tests/rest/client/test_identity.py +67 -0
  1473. tests/rest/client/test_keys.py +516 -0
  1474. tests/rest/client/test_login.py +1881 -0
  1475. tests/rest/client/test_login_token_request.py +175 -0
  1476. tests/rest/client/test_matrixrtc.py +105 -0
  1477. tests/rest/client/test_media.py +3156 -0
  1478. tests/rest/client/test_models.py +83 -0
  1479. tests/rest/client/test_mutual_rooms.py +235 -0
  1480. tests/rest/client/test_notifications.py +231 -0
  1481. tests/rest/client/test_owned_state.py +308 -0
  1482. tests/rest/client/test_password_policy.py +186 -0
  1483. tests/rest/client/test_power_levels.py +295 -0
  1484. tests/rest/client/test_presence.py +149 -0
  1485. tests/rest/client/test_profile.py +925 -0
  1486. tests/rest/client/test_push_rule_attrs.py +510 -0
  1487. tests/rest/client/test_read_marker.py +151 -0
  1488. tests/rest/client/test_receipts.py +287 -0
  1489. tests/rest/client/test_redactions.py +657 -0
  1490. tests/rest/client/test_register.py +1314 -0
  1491. tests/rest/client/test_relations.py +1954 -0
  1492. tests/rest/client/test_rendezvous.py +468 -0
  1493. tests/rest/client/test_reporting.py +324 -0
  1494. tests/rest/client/test_retention.py +389 -0
  1495. tests/rest/client/test_rooms.py +5486 -0
  1496. tests/rest/client/test_sendtodevice.py +271 -0
  1497. tests/rest/client/test_shadow_banned.py +335 -0
  1498. tests/rest/client/test_sync.py +1147 -0
  1499. tests/rest/client/test_tags.py +161 -0
  1500. tests/rest/client/test_third_party_rules.py +1076 -0
  1501. tests/rest/client/test_thread_subscriptions.py +351 -0
  1502. tests/rest/client/test_transactions.py +204 -0
  1503. tests/rest/client/test_typing.py +114 -0
  1504. tests/rest/client/test_upgrade_room.py +433 -0
  1505. tests/rest/client/utils.py +985 -0
  1506. tests/rest/key/__init__.py +0 -0
  1507. tests/rest/key/v2/__init__.py +0 -0
  1508. tests/rest/key/v2/test_remote_key_resource.py +282 -0
  1509. tests/rest/media/__init__.py +19 -0
  1510. tests/rest/media/test_domain_blocking.py +148 -0
  1511. tests/rest/media/test_url_preview.py +1445 -0
  1512. tests/rest/synapse/__init__.py +12 -0
  1513. tests/rest/synapse/client/__init__.py +12 -0
  1514. tests/rest/synapse/client/test_federation_whitelist.py +118 -0
  1515. tests/rest/synapse/mas/__init__.py +12 -0
  1516. tests/rest/synapse/mas/_base.py +43 -0
  1517. tests/rest/synapse/mas/test_devices.py +693 -0
  1518. tests/rest/synapse/mas/test_users.py +1399 -0
  1519. tests/rest/test_health.py +35 -0
  1520. tests/rest/test_well_known.py +155 -0
  1521. tests/scripts/__init__.py +0 -0
  1522. tests/scripts/test_new_matrix_user.py +172 -0
  1523. tests/server.py +1374 -0
  1524. tests/server_notices/__init__.py +241 -0
  1525. tests/server_notices/test_consent.py +111 -0
  1526. tests/server_notices/test_resource_limits_server_notices.py +409 -0
  1527. tests/state/__init__.py +0 -0
  1528. tests/state/test_v2.py +1096 -0
  1529. tests/state/test_v21.py +506 -0
  1530. tests/storage/__init__.py +0 -0
  1531. tests/storage/databases/__init__.py +20 -0
  1532. tests/storage/databases/main/__init__.py +20 -0
  1533. tests/storage/databases/main/test_cache.py +124 -0
  1534. tests/storage/databases/main/test_deviceinbox.py +323 -0
  1535. tests/storage/databases/main/test_end_to_end_keys.py +127 -0
  1536. tests/storage/databases/main/test_events_worker.py +594 -0
  1537. tests/storage/databases/main/test_lock.py +499 -0
  1538. tests/storage/databases/main/test_metrics.py +88 -0
  1539. tests/storage/databases/main/test_receipts.py +218 -0
  1540. tests/storage/databases/main/test_room.py +192 -0
  1541. tests/storage/test__base.py +178 -0
  1542. tests/storage/test_account_data.py +186 -0
  1543. tests/storage/test_appservice.py +568 -0
  1544. tests/storage/test_background_update.py +671 -0
  1545. tests/storage/test_base.py +813 -0
  1546. tests/storage/test_cleanup_extrems.py +396 -0
  1547. tests/storage/test_client_ips.py +788 -0
  1548. tests/storage/test_database.py +288 -0
  1549. tests/storage/test_devices.py +353 -0
  1550. tests/storage/test_directory.py +74 -0
  1551. tests/storage/test_e2e_room_keys.py +87 -0
  1552. tests/storage/test_end_to_end_keys.py +120 -0
  1553. tests/storage/test_event_chain.py +826 -0
  1554. tests/storage/test_event_federation.py +1433 -0
  1555. tests/storage/test_event_push_actions.py +809 -0
  1556. tests/storage/test_events.py +591 -0
  1557. tests/storage/test_events_bg_updates.py +156 -0
  1558. tests/storage/test_id_generators.py +791 -0
  1559. tests/storage/test_invite_rule.py +171 -0
  1560. tests/storage/test_main.py +56 -0
  1561. tests/storage/test_monthly_active_users.py +500 -0
  1562. tests/storage/test_profile.py +134 -0
  1563. tests/storage/test_purge.py +459 -0
  1564. tests/storage/test_receipts.py +309 -0
  1565. tests/storage/test_redaction.py +462 -0
  1566. tests/storage/test_registration.py +277 -0
  1567. tests/storage/test_relations.py +118 -0
  1568. tests/storage/test_rollback_worker.py +132 -0
  1569. tests/storage/test_room.py +69 -0
  1570. tests/storage/test_room_search.py +383 -0
  1571. tests/storage/test_roommember.py +812 -0
  1572. tests/storage/test_sliding_sync_tables.py +5187 -0
  1573. tests/storage/test_state.py +959 -0
  1574. tests/storage/test_state_deletion.py +475 -0
  1575. tests/storage/test_stream.py +1533 -0
  1576. tests/storage/test_thread_subscriptions.py +369 -0
  1577. tests/storage/test_transactions.py +77 -0
  1578. tests/storage/test_txn_limit.py +49 -0
  1579. tests/storage/test_unsafe_locale.py +67 -0
  1580. tests/storage/test_user_directory.py +691 -0
  1581. tests/storage/test_user_filters.py +101 -0
  1582. tests/storage/util/__init__.py +20 -0
  1583. tests/storage/util/test_partial_state_events_tracker.py +181 -0
  1584. tests/synapse_rust/__init__.py +11 -0
  1585. tests/synapse_rust/test_http_client.py +225 -0
  1586. tests/test_distributor.py +74 -0
  1587. tests/test_event_auth.py +921 -0
  1588. tests/test_mau.py +347 -0
  1589. tests/test_phone_home.py +102 -0
  1590. tests/test_rust.py +11 -0
  1591. tests/test_server.py +557 -0
  1592. tests/test_state.py +902 -0
  1593. tests/test_terms_auth.py +128 -0
  1594. tests/test_types.py +201 -0
  1595. tests/test_utils/__init__.py +161 -0
  1596. tests/test_utils/event_injection.py +150 -0
  1597. tests/test_utils/html_parsers.py +59 -0
  1598. tests/test_utils/logging_setup.py +74 -0
  1599. tests/test_utils/oidc.py +370 -0
  1600. tests/test_visibility.py +712 -0
  1601. tests/types/__init__.py +0 -0
  1602. tests/types/test_init.py +51 -0
  1603. tests/types/test_state.py +627 -0
  1604. tests/unittest.py +1108 -0
  1605. tests/util/__init__.py +20 -0
  1606. tests/util/caches/__init__.py +20 -0
  1607. tests/util/caches/test_cached_call.py +168 -0
  1608. tests/util/caches/test_deferred_cache.py +317 -0
  1609. tests/util/caches/test_descriptors.py +1110 -0
  1610. tests/util/caches/test_response_cache.py +225 -0
  1611. tests/util/caches/test_ttlcache.py +90 -0
  1612. tests/util/test_async_helpers.py +808 -0
  1613. tests/util/test_background_queue.py +117 -0
  1614. tests/util/test_batching_queue.py +252 -0
  1615. tests/util/test_check_dependencies.py +243 -0
  1616. tests/util/test_dict_cache.py +130 -0
  1617. tests/util/test_events.py +118 -0
  1618. tests/util/test_expiring_cache.py +113 -0
  1619. tests/util/test_file_consumer.py +199 -0
  1620. tests/util/test_itertools.py +190 -0
  1621. tests/util/test_linearizer.py +264 -0
  1622. tests/util/test_logcontext.py +715 -0
  1623. tests/util/test_logformatter.py +44 -0
  1624. tests/util/test_lrucache.py +479 -0
  1625. tests/util/test_macaroons.py +126 -0
  1626. tests/util/test_mutable_overlay_mapping.py +189 -0
  1627. tests/util/test_ratelimitutils.py +146 -0
  1628. tests/util/test_retryutils.py +314 -0
  1629. tests/util/test_rwlock.py +401 -0
  1630. tests/util/test_stream_change_cache.py +304 -0
  1631. tests/util/test_stringutils.py +86 -0
  1632. tests/util/test_task_scheduler.py +227 -0
  1633. tests/util/test_threepids.py +55 -0
  1634. tests/util/test_treecache.py +93 -0
  1635. tests/util/test_wheel_timer.py +82 -0
  1636. tests/utils.py +342 -0
@@ -0,0 +1,3765 @@
1
+ #
2
+ # This file is licensed under the Affero General Public License (AGPL) version 3.
3
+ #
4
+ # Copyright 2019-2021 The Matrix.org Foundation C.I.C.
5
+ # Copyright 2014-2016 OpenMarket Ltd
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
+ import collections
23
+ import itertools
24
+ import logging
25
+ from collections import OrderedDict
26
+ from typing import (
27
+ TYPE_CHECKING,
28
+ Any,
29
+ Collection,
30
+ Generator,
31
+ Iterable,
32
+ Sequence,
33
+ TypedDict,
34
+ cast,
35
+ )
36
+
37
+ import attr
38
+ from prometheus_client import Counter
39
+
40
+ import synapse.metrics
41
+ from synapse.api.constants import (
42
+ EventContentFields,
43
+ EventTypes,
44
+ Membership,
45
+ RelationTypes,
46
+ )
47
+ from synapse.api.errors import PartialStateConflictError
48
+ from synapse.api.room_versions import RoomVersions
49
+ from synapse.events import (
50
+ EventBase,
51
+ StrippedStateEvent,
52
+ is_creator,
53
+ relation_from_event,
54
+ )
55
+ from synapse.events.snapshot import EventPersistencePair
56
+ from synapse.events.utils import parse_stripped_state_event
57
+ from synapse.logging.opentracing import trace
58
+ from synapse.metrics import SERVER_NAME_LABEL
59
+ from synapse.storage._base import db_to_json, make_in_list_sql_clause
60
+ from synapse.storage.database import (
61
+ DatabasePool,
62
+ LoggingDatabaseConnection,
63
+ LoggingTransaction,
64
+ make_tuple_in_list_sql_clause,
65
+ )
66
+ from synapse.storage.databases.main.event_federation import EventFederationStore
67
+ from synapse.storage.databases.main.events_worker import EventCacheEntry
68
+ from synapse.storage.databases.main.search import SearchEntry
69
+ from synapse.storage.engines import PostgresEngine
70
+ from synapse.storage.util.id_generators import AbstractStreamIdGenerator
71
+ from synapse.storage.util.sequence import SequenceGenerator
72
+ from synapse.types import (
73
+ JsonDict,
74
+ MutableStateMap,
75
+ StateMap,
76
+ StrCollection,
77
+ )
78
+ from synapse.types.handlers import SLIDING_SYNC_DEFAULT_BUMP_EVENT_TYPES
79
+ from synapse.types.state import StateFilter
80
+ from synapse.util.events import get_plain_text_topic_from_event_content
81
+ from synapse.util.iterutils import batch_iter, sorted_topologically
82
+ from synapse.util.json import json_encoder
83
+ from synapse.util.stringutils import non_null_str_or_none
84
+
85
+ if TYPE_CHECKING:
86
+ from synapse.server import HomeServer
87
+ from synapse.storage.databases.main import DataStore
88
+
89
+
90
+ logger = logging.getLogger(__name__)
91
+
92
+ persist_event_counter = Counter(
93
+ "synapse_storage_events_persisted_events", "", labelnames=[SERVER_NAME_LABEL]
94
+ )
95
+ event_counter = Counter(
96
+ "synapse_storage_events_persisted_events_sep",
97
+ "",
98
+ labelnames=[
99
+ "type", # The event type or "*other*" for types we don't track
100
+ "origin_type",
101
+ SERVER_NAME_LABEL,
102
+ ],
103
+ )
104
+
105
+ # Event types that we track in the `events_counter` metric above.
106
+ #
107
+ # This list is chosen to balance tracking the most common event types that are
108
+ # useful to monitor (and are likely to spike), while keeping the cardinality of
109
+ # the metric low enough to avoid wasted resources.
110
+ TRACKED_EVENT_TYPES = {
111
+ EventTypes.Message,
112
+ EventTypes.Encrypted,
113
+ EventTypes.Member,
114
+ EventTypes.ThirdPartyInvite,
115
+ EventTypes.Redaction,
116
+ EventTypes.Create,
117
+ EventTypes.Tombstone,
118
+ }
119
+
120
+ # State event type/key pairs that we need to gather to fill in the
121
+ # `sliding_sync_joined_rooms`/`sliding_sync_membership_snapshots` tables.
122
+ SLIDING_SYNC_RELEVANT_STATE_SET = (
123
+ # So we can fill in the `room_type` column
124
+ (EventTypes.Create, ""),
125
+ # So we can fill in the `is_encrypted` column
126
+ (EventTypes.RoomEncryption, ""),
127
+ # So we can fill in the `room_name` column
128
+ (EventTypes.Name, ""),
129
+ # So we can fill in the `tombstone_successor_room_id` column
130
+ (EventTypes.Tombstone, ""),
131
+ )
132
+
133
+
134
+ @attr.s(slots=True, auto_attribs=True)
135
+ class DeltaState:
136
+ """Deltas to use to update the `current_state_events` table.
137
+
138
+ Attributes:
139
+ to_delete: List of type/state_keys to delete from current state
140
+ to_insert: Map of state to upsert into current state
141
+ no_longer_in_room: The server is no longer in the room, so the room
142
+ should e.g. be removed from `current_state_events` table.
143
+ """
144
+
145
+ to_delete: list[tuple[str, str]]
146
+ to_insert: StateMap[str]
147
+ no_longer_in_room: bool = False
148
+
149
+ def is_noop(self) -> bool:
150
+ """Whether this state delta is actually empty"""
151
+ return not self.to_delete and not self.to_insert and not self.no_longer_in_room
152
+
153
+
154
+ # We want `total=False` because we want to allow values to be unset.
155
+ class SlidingSyncStateInsertValues(TypedDict, total=False):
156
+ """
157
+ Insert values relevant for the `sliding_sync_joined_rooms` and
158
+ `sliding_sync_membership_snapshots` database tables.
159
+ """
160
+
161
+ room_type: str | None
162
+ is_encrypted: bool | None
163
+ room_name: str | None
164
+ tombstone_successor_room_id: str | None
165
+
166
+
167
+ class SlidingSyncMembershipSnapshotSharedInsertValues(
168
+ SlidingSyncStateInsertValues, total=False
169
+ ):
170
+ """
171
+ Insert values for `sliding_sync_membership_snapshots` that we can share across
172
+ multiple memberships
173
+ """
174
+
175
+ has_known_state: bool | None
176
+
177
+
178
+ @attr.s(slots=True, auto_attribs=True)
179
+ class SlidingSyncMembershipInfo:
180
+ """
181
+ Values unique to each membership
182
+ """
183
+
184
+ user_id: str
185
+ sender: str
186
+ membership_event_id: str
187
+ membership: str
188
+
189
+
190
+ @attr.s(slots=True, auto_attribs=True)
191
+ class SlidingSyncMembershipInfoWithEventPos(SlidingSyncMembershipInfo):
192
+ """
193
+ SlidingSyncMembershipInfo + `stream_ordering`/`instance_name` of the membership
194
+ event
195
+ """
196
+
197
+ membership_event_stream_ordering: int
198
+ membership_event_instance_name: str
199
+
200
+
201
+ @attr.s(slots=True, auto_attribs=True)
202
+ class SlidingSyncTableChanges:
203
+ room_id: str
204
+ # If the row doesn't exist in the `sliding_sync_joined_rooms` table, we need to
205
+ # fully-insert it which means we also need to include a `bump_stamp` value to use
206
+ # for the row. This should only be populated when we're trying to fully-insert a
207
+ # row.
208
+ #
209
+ # FIXME: This can be removed once we bump `SCHEMA_COMPAT_VERSION` and run the
210
+ # foreground update for
211
+ # `sliding_sync_joined_rooms`/`sliding_sync_membership_snapshots` (tracked by
212
+ # https://github.com/element-hq/synapse/issues/17623)
213
+ joined_room_bump_stamp_to_fully_insert: int | None
214
+ # Values to upsert into `sliding_sync_joined_rooms`
215
+ joined_room_updates: SlidingSyncStateInsertValues
216
+
217
+ # Shared values to upsert into `sliding_sync_membership_snapshots` for each
218
+ # `to_insert_membership_snapshots`
219
+ membership_snapshot_shared_insert_values: (
220
+ SlidingSyncMembershipSnapshotSharedInsertValues
221
+ )
222
+ # List of membership to insert into `sliding_sync_membership_snapshots`
223
+ to_insert_membership_snapshots: list[SlidingSyncMembershipInfo]
224
+ # List of user_id to delete from `sliding_sync_membership_snapshots`
225
+ to_delete_membership_snapshots: list[str]
226
+
227
+
228
+ @attr.s(slots=True, auto_attribs=True)
229
+ class NewEventChainLinks:
230
+ """Information about new auth chain links that need to be added to the DB.
231
+
232
+ Attributes:
233
+ chain_id, sequence_number: the IDs corresponding to the event being
234
+ inserted, and the starting point of the links
235
+ links: Lists the links that need to be added, 2-tuple of the chain
236
+ ID/sequence number of the end point of the link.
237
+ """
238
+
239
+ chain_id: int
240
+ sequence_number: int
241
+
242
+ links: list[tuple[int, int]] = attr.Factory(list)
243
+
244
+
245
+ class PersistEventsStore:
246
+ """Contains all the functions for writing events to the database.
247
+
248
+ Should only be instantiated on one process (when using a worker mode setup).
249
+
250
+ Note: This is not part of the `DataStore` mixin.
251
+ """
252
+
253
+ def __init__(
254
+ self,
255
+ hs: "HomeServer",
256
+ db: DatabasePool,
257
+ main_data_store: "DataStore",
258
+ db_conn: LoggingDatabaseConnection,
259
+ ):
260
+ self.hs = hs
261
+ self.server_name = hs.hostname
262
+ self.db_pool = db
263
+ self.store = main_data_store
264
+ self.database_engine = db.engine
265
+ self._clock = hs.get_clock()
266
+ self._instance_name = hs.get_instance_name()
267
+
268
+ self._ephemeral_messages_enabled = hs.config.server.enable_ephemeral_messages
269
+ self.is_mine_id = hs.is_mine_id
270
+
271
+ # This should only exist on instances that are configured to write
272
+ assert hs.get_instance_name() in hs.config.worker.writers.events, (
273
+ "Can only instantiate EventsStore on master"
274
+ )
275
+
276
+ # Since we have been configured to write, we ought to have id generators,
277
+ # rather than id trackers.
278
+ assert isinstance(self.store._backfill_id_gen, AbstractStreamIdGenerator)
279
+ assert isinstance(self.store._stream_id_gen, AbstractStreamIdGenerator)
280
+
281
+ # Ideally we'd move these ID gens here, unfortunately some other ID
282
+ # generators are chained off them so doing so is a bit of a PITA.
283
+ self._backfill_id_gen: AbstractStreamIdGenerator = self.store._backfill_id_gen
284
+ self._stream_id_gen: AbstractStreamIdGenerator = self.store._stream_id_gen
285
+
286
+ @trace
287
+ async def _persist_events_and_state_updates(
288
+ self,
289
+ room_id: str,
290
+ events_and_contexts: list[EventPersistencePair],
291
+ *,
292
+ state_delta_for_room: DeltaState | None,
293
+ new_forward_extremities: set[str] | None,
294
+ new_event_links: dict[str, NewEventChainLinks],
295
+ use_negative_stream_ordering: bool = False,
296
+ inhibit_local_membership_updates: bool = False,
297
+ ) -> None:
298
+ """Persist a set of events alongside updates to the current state and
299
+ forward extremities tables.
300
+
301
+ Assumes that we are only persisting events for one room at a time.
302
+
303
+ Args:
304
+ room_id:
305
+ events_and_contexts:
306
+ state_delta_for_room: The delta to apply to the room state
307
+ new_forward_extremities: A set of event IDs that are the new forward
308
+ extremities of the room.
309
+ use_negative_stream_ordering: Whether to start stream_ordering on
310
+ the negative side and decrement. This should be set as True
311
+ for backfilled events because backfilled events get a negative
312
+ stream ordering so they don't come down incremental `/sync`.
313
+ inhibit_local_membership_updates: Stop the local_current_membership
314
+ from being updated by these events. This should be set to True
315
+ for backfilled events because backfilled events in the past do
316
+ not affect the current local state.
317
+
318
+ Returns:
319
+ Resolves when the events have been persisted
320
+
321
+ Raises:
322
+ PartialStateConflictError: if attempting to persist a partial state event in
323
+ a room that has been un-partial stated.
324
+ """
325
+
326
+ # We want to calculate the stream orderings as late as possible, as
327
+ # we only notify after all events with a lesser stream ordering have
328
+ # been persisted. I.e. if we spend 10s inside the with block then
329
+ # that will delay all subsequent events from being notified about.
330
+ # Hence why we do it down here rather than wrapping the entire
331
+ # function.
332
+ #
333
+ # Its safe to do this after calculating the state deltas etc as we
334
+ # only need to protect the *persistence* of the events. This is to
335
+ # ensure that queries of the form "fetch events since X" don't
336
+ # return events and stream positions after events that are still in
337
+ # flight, as otherwise subsequent requests "fetch event since Y"
338
+ # will not return those events.
339
+ #
340
+ # Note: Multiple instances of this function cannot be in flight at
341
+ # the same time for the same room.
342
+ if use_negative_stream_ordering:
343
+ stream_ordering_manager = self._backfill_id_gen.get_next_mult(
344
+ len(events_and_contexts)
345
+ )
346
+ else:
347
+ stream_ordering_manager = self._stream_id_gen.get_next_mult(
348
+ len(events_and_contexts)
349
+ )
350
+
351
+ async with stream_ordering_manager as stream_orderings:
352
+ for (event, _), stream in zip(events_and_contexts, stream_orderings):
353
+ # XXX: We can't rely on `stream_ordering`/`instance_name` being correct
354
+ # at this point. We could be working with events that were previously
355
+ # persisted as an `outlier` with one `stream_ordering` but are now being
356
+ # persisted again and de-outliered and are being assigned a different
357
+ # `stream_ordering` here that won't end up being used.
358
+ # `_update_outliers_txn()` will fix this discrepancy (always use the
359
+ # `stream_ordering` from the first time it was persisted).
360
+ event.internal_metadata.stream_ordering = stream
361
+ event.internal_metadata.instance_name = self._instance_name
362
+
363
+ sliding_sync_table_changes = None
364
+ if state_delta_for_room is not None:
365
+ sliding_sync_table_changes = (
366
+ await self._calculate_sliding_sync_table_changes(
367
+ room_id, events_and_contexts, state_delta_for_room
368
+ )
369
+ )
370
+
371
+ await self.db_pool.runInteraction(
372
+ "persist_events",
373
+ self._persist_events_txn,
374
+ room_id=room_id,
375
+ events_and_contexts=events_and_contexts,
376
+ inhibit_local_membership_updates=inhibit_local_membership_updates,
377
+ state_delta_for_room=state_delta_for_room,
378
+ new_forward_extremities=new_forward_extremities,
379
+ new_event_links=new_event_links,
380
+ sliding_sync_table_changes=sliding_sync_table_changes,
381
+ )
382
+ persist_event_counter.labels(**{SERVER_NAME_LABEL: self.server_name}).inc(
383
+ len(events_and_contexts)
384
+ )
385
+
386
+ if not use_negative_stream_ordering:
387
+ # we don't want to set the event_persisted_position to a negative
388
+ # stream_ordering.
389
+ synapse.metrics.event_persisted_position.labels(
390
+ **{SERVER_NAME_LABEL: self.server_name}
391
+ ).set(stream)
392
+
393
+ for event, context in events_and_contexts:
394
+ if context.app_service:
395
+ origin_type = "application_service"
396
+ elif self.hs.is_mine_id(event.sender):
397
+ origin_type = "local"
398
+ else:
399
+ origin_type = "remote"
400
+
401
+ # We only track a subset of event types, to avoid high
402
+ # cardinality in the metrics.
403
+ metrics_event_type = (
404
+ event.type if event.type in TRACKED_EVENT_TYPES else "*other*"
405
+ )
406
+
407
+ event_counter.labels(
408
+ type=metrics_event_type,
409
+ origin_type=origin_type,
410
+ **{SERVER_NAME_LABEL: self.server_name},
411
+ ).inc()
412
+
413
+ if (
414
+ not self.hs.config.experimental.msc4293_enabled
415
+ or event.type != EventTypes.Member
416
+ or event.state_key is None
417
+ ):
418
+ continue
419
+
420
+ # check if this is an unban/join that will undo a ban/kick redaction for
421
+ # a user in the room
422
+ if event.membership in [Membership.LEAVE, Membership.JOIN]:
423
+ if (
424
+ event.membership == Membership.LEAVE
425
+ and event.sender == event.state_key
426
+ ):
427
+ # self-leave, ignore
428
+ continue
429
+
430
+ # if there is an existing ban/leave causing redactions for
431
+ # this user/room combination update the entry with the stream
432
+ # ordering when the redactions should stop - in the case of a backfilled
433
+ # event where the stream ordering is negative, use the current max stream
434
+ # ordering
435
+ stream_ordering = event.internal_metadata.stream_ordering
436
+ assert stream_ordering is not None
437
+ if stream_ordering < 0:
438
+ stream_ordering = self._stream_id_gen.get_current_token()
439
+ await self.db_pool.simple_update(
440
+ "room_ban_redactions",
441
+ {"room_id": event.room_id, "user_id": event.state_key},
442
+ {"redact_end_ordering": stream_ordering},
443
+ desc="room_ban_redactions update redact_end_ordering",
444
+ )
445
+
446
+ # check for msc4293 redact_events flag and apply if found
447
+ if event.membership not in [Membership.LEAVE, Membership.BAN]:
448
+ continue
449
+ redact = event.content.get("org.matrix.msc4293.redact_events", False)
450
+ if not redact or not isinstance(redact, bool):
451
+ continue
452
+ # self-bans currently are not authorized so we don't check for that
453
+ # case
454
+ if (
455
+ event.membership == Membership.BAN
456
+ and event.sender == event.state_key
457
+ ):
458
+ continue
459
+
460
+ # check that sender can redact
461
+ redact_allowed = await self._can_sender_redact(event)
462
+
463
+ # Signal that this user's past events in this room
464
+ # should be redacted by adding an entry to
465
+ # `room_ban_redactions`.
466
+ if redact_allowed:
467
+ await self.db_pool.simple_upsert(
468
+ "room_ban_redactions",
469
+ {"room_id": event.room_id, "user_id": event.state_key},
470
+ {
471
+ "redacting_event_id": event.event_id,
472
+ "redact_end_ordering": None,
473
+ },
474
+ {
475
+ "room_id": event.room_id,
476
+ "user_id": event.state_key,
477
+ "redacting_event_id": event.event_id,
478
+ "redact_end_ordering": None,
479
+ },
480
+ )
481
+
482
+ # normally the cache entry for a redacted event would be invalidated
483
+ # by an arriving redaction event, but since we are not creating redaction
484
+ # events we invalidate manually
485
+ self.store._invalidate_local_get_event_cache_room_id(event.room_id)
486
+
487
+ self.store._invalidate_async_get_event_cache_room_id(event.room_id)
488
+
489
+ if new_forward_extremities:
490
+ self.store.get_latest_event_ids_in_room.prefill(
491
+ (room_id,), frozenset(new_forward_extremities)
492
+ )
493
+
494
+ async def _can_sender_redact(self, event: EventBase) -> bool:
495
+ state_filter = StateFilter.from_types(
496
+ [(EventTypes.PowerLevels, ""), (EventTypes.Create, "")]
497
+ )
498
+ state = await self.store.get_partial_filtered_current_state_ids(
499
+ event.room_id, state_filter
500
+ )
501
+ pl_id = state[(EventTypes.PowerLevels, "")]
502
+ pl_event = await self.store.get_event(pl_id, allow_none=True)
503
+
504
+ create_id = state[(EventTypes.Create, "")]
505
+ create_event = await self.store.get_event(create_id, allow_none=True)
506
+
507
+ if create_event is None:
508
+ # not sure how this would happen but if it does then just deny the redaction
509
+ logger.warning("No create event found for room %s", event.room_id)
510
+ return False
511
+
512
+ if create_event.room_version.msc4289_creator_power_enabled:
513
+ # per the spec, grant the creator infinite power level and all other users 0
514
+ if is_creator(create_event, event.sender):
515
+ return True
516
+ if pl_event is None:
517
+ # per the spec, users other than the room creator have power level
518
+ # 0, which is less than the default to redact events (50).
519
+ return False
520
+ else:
521
+ # per the spec, if a power level event isn't in the room, grant the creator
522
+ # level 100 (the default redaction level is 50) and all other users 0
523
+ if pl_event is None:
524
+ return create_event.sender == event.sender
525
+
526
+ assert pl_event is not None
527
+ sender_level = pl_event.content.get("users", {}).get(event.sender)
528
+ if sender_level is None:
529
+ sender_level = pl_event.content.get("users_default", 0)
530
+
531
+ redact_level = pl_event.content.get("redact")
532
+ if redact_level is None:
533
+ redact_level = pl_event.content.get("events_default", 0)
534
+
535
+ room_redaction_level = pl_event.content.get("events", {}).get(
536
+ "m.room.redaction"
537
+ )
538
+ if room_redaction_level is not None:
539
+ if sender_level < room_redaction_level:
540
+ return False
541
+
542
+ if sender_level >= redact_level:
543
+ return True
544
+
545
+ return False
546
+
547
+ async def _calculate_sliding_sync_table_changes(
548
+ self,
549
+ room_id: str,
550
+ events_and_contexts: Sequence[EventPersistencePair],
551
+ delta_state: DeltaState,
552
+ ) -> SlidingSyncTableChanges:
553
+ """
554
+ Calculate the changes to the `sliding_sync_membership_snapshots` and
555
+ `sliding_sync_joined_rooms` tables given the deltas that are going to be used to
556
+ update the `current_state_events` table.
557
+
558
+ Just a bunch of pre-processing so we so we don't need to spend time in the
559
+ transaction itself gathering all of this info. It's also easier to deal with
560
+ redactions outside of a transaction.
561
+
562
+ Args:
563
+ room_id: The room ID currently being processed.
564
+ events_and_contexts: List of tuples of (event, context) being persisted.
565
+ This is completely optional (you can pass an empty list) and will just
566
+ save us from fetching the events from the database if we already have
567
+ them. We assume the list is sorted ascending by `stream_ordering`. We
568
+ don't care about the sort when the events are backfilled (with negative
569
+ `stream_ordering`).
570
+ delta_state: Deltas that are going to be used to update the
571
+ `current_state_events` table. Changes to the current state of the room.
572
+
573
+ Returns:
574
+ SlidingSyncTableChanges
575
+ """
576
+ to_insert = delta_state.to_insert
577
+ to_delete = delta_state.to_delete
578
+
579
+ # If no state is changing, we don't need to do anything. This can happen when a
580
+ # partial-stated room is re-syncing the current state.
581
+ if not to_insert and not to_delete:
582
+ return SlidingSyncTableChanges(
583
+ room_id=room_id,
584
+ joined_room_bump_stamp_to_fully_insert=None,
585
+ joined_room_updates={},
586
+ membership_snapshot_shared_insert_values={},
587
+ to_insert_membership_snapshots=[],
588
+ to_delete_membership_snapshots=[],
589
+ )
590
+
591
+ event_map = {event.event_id: event for event, _ in events_and_contexts}
592
+
593
+ # Handle gathering info for the `sliding_sync_membership_snapshots` table
594
+ #
595
+ # This would only happen if someone was state reset out of the room
596
+ user_ids_to_delete_membership_snapshots = [
597
+ state_key
598
+ for event_type, state_key in to_delete
599
+ if event_type == EventTypes.Member and self.is_mine_id(state_key)
600
+ ]
601
+
602
+ membership_snapshot_shared_insert_values: SlidingSyncMembershipSnapshotSharedInsertValues = {}
603
+ membership_infos_to_insert_membership_snapshots: list[
604
+ SlidingSyncMembershipInfo
605
+ ] = []
606
+ if to_insert:
607
+ membership_event_id_to_user_id_map: dict[str, str] = {}
608
+ for state_key, event_id in to_insert.items():
609
+ if state_key[0] == EventTypes.Member and self.is_mine_id(state_key[1]):
610
+ membership_event_id_to_user_id_map[event_id] = state_key[1]
611
+
612
+ membership_event_map: dict[str, EventBase] = {}
613
+ # In normal event persist scenarios, we should be able to find the
614
+ # membership events in the `events_and_contexts` given to us but it's
615
+ # possible a state reset happened which added us to the room without a
616
+ # corresponding new membership event (reset back to a previous membership).
617
+ missing_membership_event_ids: set[str] = set()
618
+ for membership_event_id in membership_event_id_to_user_id_map.keys():
619
+ membership_event = event_map.get(membership_event_id)
620
+ if membership_event:
621
+ membership_event_map[membership_event_id] = membership_event
622
+ else:
623
+ missing_membership_event_ids.add(membership_event_id)
624
+
625
+ # Otherwise, we need to find a couple events that we were reset to.
626
+ if missing_membership_event_ids:
627
+ remaining_events = await self.store.get_events(
628
+ missing_membership_event_ids
629
+ )
630
+ # There shouldn't be any missing events
631
+ assert remaining_events.keys() == missing_membership_event_ids, (
632
+ missing_membership_event_ids.difference(remaining_events.keys())
633
+ )
634
+ membership_event_map.update(remaining_events)
635
+
636
+ for (
637
+ membership_event_id,
638
+ user_id,
639
+ ) in membership_event_id_to_user_id_map.items():
640
+ membership_infos_to_insert_membership_snapshots.append(
641
+ # XXX: We don't use `SlidingSyncMembershipInfoWithEventPos` here
642
+ # because we're sourcing the event from `events_and_contexts`, we
643
+ # can't rely on `stream_ordering`/`instance_name` being correct at
644
+ # this point. We could be working with events that were previously
645
+ # persisted as an `outlier` with one `stream_ordering` but are now
646
+ # being persisted again and de-outliered and assigned a different
647
+ # `stream_ordering` that won't end up being used. Since we call
648
+ # `_calculate_sliding_sync_table_changes()` before
649
+ # `_update_outliers_txn()` which fixes this discrepancy (always use
650
+ # the `stream_ordering` from the first time it was persisted), we're
651
+ # working with an unreliable `stream_ordering` value that will
652
+ # possibly be unused and not make it into the `events` table.
653
+ SlidingSyncMembershipInfo(
654
+ user_id=user_id,
655
+ sender=membership_event_map[membership_event_id].sender,
656
+ membership_event_id=membership_event_id,
657
+ membership=membership_event_map[membership_event_id].membership,
658
+ )
659
+ )
660
+
661
+ if membership_infos_to_insert_membership_snapshots:
662
+ current_state_ids_map: MutableStateMap[str] = dict(
663
+ await self.store.get_partial_filtered_current_state_ids(
664
+ room_id,
665
+ state_filter=StateFilter.from_types(
666
+ SLIDING_SYNC_RELEVANT_STATE_SET
667
+ ),
668
+ )
669
+ )
670
+ # Since we fetched the current state before we took `to_insert`/`to_delete`
671
+ # into account, we need to do a couple fixups.
672
+ #
673
+ # Update the current_state_map with what we have `to_delete`
674
+ for state_key in to_delete:
675
+ current_state_ids_map.pop(state_key, None)
676
+ # Update the current_state_map with what we have `to_insert`
677
+ for state_key, event_id in to_insert.items():
678
+ if state_key in SLIDING_SYNC_RELEVANT_STATE_SET:
679
+ current_state_ids_map[state_key] = event_id
680
+
681
+ current_state_map: MutableStateMap[EventBase] = {}
682
+ # In normal event persist scenarios, we probably won't be able to find
683
+ # these state events in `events_and_contexts` since we don't generally
684
+ # batch up local membership changes with other events, but it can
685
+ # happen.
686
+ missing_state_event_ids: set[str] = set()
687
+ for state_key, event_id in current_state_ids_map.items():
688
+ event = event_map.get(event_id)
689
+ if event:
690
+ current_state_map[state_key] = event
691
+ else:
692
+ missing_state_event_ids.add(event_id)
693
+
694
+ # Otherwise, we need to find a couple events
695
+ if missing_state_event_ids:
696
+ remaining_events = await self.store.get_events(
697
+ missing_state_event_ids
698
+ )
699
+ # There shouldn't be any missing events
700
+ assert remaining_events.keys() == missing_state_event_ids, (
701
+ missing_state_event_ids.difference(remaining_events.keys())
702
+ )
703
+ for event in remaining_events.values():
704
+ current_state_map[(event.type, event.state_key)] = event
705
+
706
+ if current_state_map:
707
+ state_insert_values = PersistEventsStore._get_sliding_sync_insert_values_from_state_map(
708
+ current_state_map
709
+ )
710
+ membership_snapshot_shared_insert_values.update(state_insert_values)
711
+ # We have current state to work from
712
+ membership_snapshot_shared_insert_values["has_known_state"] = True
713
+ else:
714
+ # We don't have any `current_state_events` anymore (previously
715
+ # cleared out because of `no_longer_in_room`). This can happen if
716
+ # one user is joined and another is invited (some non-join
717
+ # membership). If the joined user leaves, we are `no_longer_in_room`
718
+ # and `current_state_events` is cleared out. When the invited user
719
+ # rejects the invite (leaves the room), we will end up here.
720
+ #
721
+ # In these cases, we should inherit the meta data from the previous
722
+ # snapshot so we shouldn't update any of the state values. When
723
+ # using sliding sync filters, this will prevent the room from
724
+ # disappearing/appearing just because you left the room.
725
+ #
726
+ # Ideally, we could additionally assert that we're only here for
727
+ # valid non-join membership transitions.
728
+ assert delta_state.no_longer_in_room
729
+
730
+ # Handle gathering info for the `sliding_sync_joined_rooms` table
731
+ #
732
+ # We only deal with
733
+ # updating the state related columns. The
734
+ # `event_stream_ordering`/`bump_stamp` are updated elsewhere in the event
735
+ # persisting stack (see
736
+ # `_update_sliding_sync_tables_with_new_persisted_events_txn()`)
737
+ #
738
+ joined_room_updates: SlidingSyncStateInsertValues = {}
739
+ bump_stamp_to_fully_insert: int | None = None
740
+ if not delta_state.no_longer_in_room:
741
+ current_state_ids_map = {}
742
+
743
+ # Always fully-insert rows if they don't already exist in the
744
+ # `sliding_sync_joined_rooms` table. This way we can rely on a row if it
745
+ # exists in the table.
746
+ #
747
+ # FIXME: This can be removed once we bump `SCHEMA_COMPAT_VERSION` and run the
748
+ # foreground update for
749
+ # `sliding_sync_joined_rooms`/`sliding_sync_membership_snapshots` (tracked by
750
+ # https://github.com/element-hq/synapse/issues/17623)
751
+ existing_row_in_table = await self.store.db_pool.simple_select_one_onecol(
752
+ table="sliding_sync_joined_rooms",
753
+ keyvalues={"room_id": room_id},
754
+ retcol="room_id",
755
+ allow_none=True,
756
+ )
757
+ if not existing_row_in_table:
758
+ most_recent_bump_event_pos_results = (
759
+ await self.store.get_last_event_pos_in_room(
760
+ room_id,
761
+ event_types=SLIDING_SYNC_DEFAULT_BUMP_EVENT_TYPES,
762
+ )
763
+ )
764
+ if most_recent_bump_event_pos_results is not None:
765
+ _, new_bump_event_pos = most_recent_bump_event_pos_results
766
+
767
+ # If we've just joined a remote room, then the last bump event may
768
+ # have been backfilled (and so have a negative stream ordering).
769
+ # These negative stream orderings can't sensibly be compared, so
770
+ # instead just leave it as `None` in the table and we will use their
771
+ # membership event position as the bump event position in the
772
+ # Sliding Sync API.
773
+ if new_bump_event_pos.stream > 0:
774
+ bump_stamp_to_fully_insert = new_bump_event_pos.stream
775
+
776
+ current_state_ids_map = dict(
777
+ await self.store.get_partial_filtered_current_state_ids(
778
+ room_id,
779
+ state_filter=StateFilter.from_types(
780
+ SLIDING_SYNC_RELEVANT_STATE_SET
781
+ ),
782
+ )
783
+ )
784
+
785
+ # Look through the items we're going to insert into the current state to see
786
+ # if there is anything that we care about and should also update in the
787
+ # `sliding_sync_joined_rooms` table.
788
+ for state_key, event_id in to_insert.items():
789
+ if state_key in SLIDING_SYNC_RELEVANT_STATE_SET:
790
+ current_state_ids_map[state_key] = event_id
791
+
792
+ # Get the full event objects for the current state events
793
+ #
794
+ # In normal event persist scenarios, we should be able to find the state
795
+ # events in the `events_and_contexts` given to us but it's possible a state
796
+ # reset happened which that reset back to a previous state.
797
+ current_state_map = {}
798
+ missing_event_ids: set[str] = set()
799
+ for state_key, event_id in current_state_ids_map.items():
800
+ event = event_map.get(event_id)
801
+ if event:
802
+ current_state_map[state_key] = event
803
+ else:
804
+ missing_event_ids.add(event_id)
805
+
806
+ # Otherwise, we need to find a couple events that we were reset to.
807
+ if missing_event_ids:
808
+ remaining_events = await self.store.get_events(missing_event_ids)
809
+ # There shouldn't be any missing events
810
+ assert remaining_events.keys() == missing_event_ids, (
811
+ missing_event_ids.difference(remaining_events.keys())
812
+ )
813
+ for event in remaining_events.values():
814
+ current_state_map[(event.type, event.state_key)] = event
815
+
816
+ joined_room_updates = (
817
+ PersistEventsStore._get_sliding_sync_insert_values_from_state_map(
818
+ current_state_map
819
+ )
820
+ )
821
+
822
+ # If something is being deleted from the state, we need to clear it out
823
+ for state_key in to_delete:
824
+ if state_key == (EventTypes.Create, ""):
825
+ joined_room_updates["room_type"] = None
826
+ elif state_key == (EventTypes.RoomEncryption, ""):
827
+ joined_room_updates["is_encrypted"] = False
828
+ elif state_key == (EventTypes.Name, ""):
829
+ joined_room_updates["room_name"] = None
830
+
831
+ return SlidingSyncTableChanges(
832
+ room_id=room_id,
833
+ # For `sliding_sync_joined_rooms`
834
+ joined_room_bump_stamp_to_fully_insert=bump_stamp_to_fully_insert,
835
+ joined_room_updates=joined_room_updates,
836
+ # For `sliding_sync_membership_snapshots`
837
+ membership_snapshot_shared_insert_values=membership_snapshot_shared_insert_values,
838
+ to_insert_membership_snapshots=membership_infos_to_insert_membership_snapshots,
839
+ to_delete_membership_snapshots=user_ids_to_delete_membership_snapshots,
840
+ )
841
+
842
+ async def calculate_chain_cover_index_for_events(
843
+ self, room_id: str, events: Collection[EventBase]
844
+ ) -> dict[str, NewEventChainLinks]:
845
+ # Filter to state events, and ensure there are no duplicates.
846
+ state_events = []
847
+ seen_events = set()
848
+ for event in events:
849
+ if not event.is_state() or event.event_id in seen_events:
850
+ continue
851
+
852
+ state_events.append(event)
853
+ seen_events.add(event.event_id)
854
+
855
+ if not state_events:
856
+ return {}
857
+
858
+ return await self.db_pool.runInteraction(
859
+ "_calculate_chain_cover_index_for_events",
860
+ self.calculate_chain_cover_index_for_events_txn,
861
+ room_id,
862
+ state_events,
863
+ )
864
+
865
+ def calculate_chain_cover_index_for_events_txn(
866
+ self, txn: LoggingTransaction, room_id: str, state_events: Collection[EventBase]
867
+ ) -> dict[str, NewEventChainLinks]:
868
+ # We now calculate chain ID/sequence numbers for any state events we're
869
+ # persisting. We ignore out of band memberships as we're not in the room
870
+ # and won't have their auth chain (we'll fix it up later if we join the
871
+ # room).
872
+ #
873
+ # See: docs/auth_chain_difference_algorithm.md
874
+
875
+ # We ignore legacy rooms that we aren't filling the chain cover index
876
+ # for.
877
+ row = self.db_pool.simple_select_one_txn(
878
+ txn,
879
+ table="rooms",
880
+ keyvalues={"room_id": room_id},
881
+ retcols=("room_id", "has_auth_chain_index"),
882
+ allow_none=True,
883
+ )
884
+ if row is None or row[1] is False:
885
+ return {}
886
+
887
+ # Filter out events that we've already calculated.
888
+ rows = self.db_pool.simple_select_many_txn(
889
+ txn,
890
+ table="event_auth_chains",
891
+ column="event_id",
892
+ iterable=[e.event_id for e in state_events],
893
+ keyvalues={},
894
+ retcols=("event_id",),
895
+ )
896
+ already_persisted_events = {event_id for (event_id,) in rows}
897
+ state_events = [
898
+ event
899
+ for event in state_events
900
+ if event.event_id not in already_persisted_events
901
+ ]
902
+
903
+ if not state_events:
904
+ return {}
905
+
906
+ # We need to know the type/state_key and auth events of the events we're
907
+ # calculating chain IDs for. We don't rely on having the full Event
908
+ # instances as we'll potentially be pulling more events from the DB and
909
+ # we don't need the overhead of fetching/parsing the full event JSON.
910
+ event_to_types = {e.event_id: (e.type, e.state_key) for e in state_events}
911
+ event_to_auth_chain = {e.event_id: e.auth_event_ids() for e in state_events}
912
+ event_to_room_id = {e.event_id: e.room_id for e in state_events}
913
+
914
+ return self._calculate_chain_cover_index(
915
+ txn,
916
+ self.db_pool,
917
+ self.store.event_chain_id_gen,
918
+ event_to_room_id,
919
+ event_to_types,
920
+ event_to_auth_chain,
921
+ )
922
+
923
+ async def _get_events_which_are_prevs(self, event_ids: Iterable[str]) -> list[str]:
924
+ """Filter the supplied list of event_ids to get those which are prev_events of
925
+ existing (non-outlier/rejected) events.
926
+
927
+ Args:
928
+ event_ids: event ids to filter
929
+
930
+ Returns:
931
+ Filtered event ids
932
+ """
933
+ results: list[str] = []
934
+
935
+ def _get_events_which_are_prevs_txn(
936
+ txn: LoggingTransaction, batch: Collection[str]
937
+ ) -> None:
938
+ sql = """
939
+ SELECT prev_event_id, internal_metadata
940
+ FROM event_edges
941
+ INNER JOIN events USING (event_id)
942
+ LEFT JOIN rejections USING (event_id)
943
+ LEFT JOIN event_json USING (event_id)
944
+ WHERE
945
+ NOT events.outlier
946
+ AND rejections.event_id IS NULL
947
+ AND
948
+ """
949
+
950
+ clause, args = make_in_list_sql_clause(
951
+ self.database_engine, "prev_event_id", batch
952
+ )
953
+
954
+ txn.execute(sql + clause, args)
955
+ results.extend(r[0] for r in txn if not db_to_json(r[1]).get("soft_failed"))
956
+
957
+ for chunk in batch_iter(event_ids, 100):
958
+ await self.db_pool.runInteraction(
959
+ "_get_events_which_are_prevs", _get_events_which_are_prevs_txn, chunk
960
+ )
961
+
962
+ return results
963
+
964
+ async def _get_prevs_before_rejected(self, event_ids: Iterable[str]) -> set[str]:
965
+ """Get soft-failed ancestors to remove from the extremities.
966
+
967
+ Given a set of events, find all those that have been soft-failed or
968
+ rejected. Returns those soft failed/rejected events and their prev
969
+ events (whether soft-failed/rejected or not), and recurses up the
970
+ prev-event graph until it finds no more soft-failed/rejected events.
971
+
972
+ This is used to find extremities that are ancestors of new events, but
973
+ are separated by soft failed events.
974
+
975
+ Args:
976
+ event_ids: Events to find prev events for. Note that these must have
977
+ already been persisted.
978
+
979
+ Returns:
980
+ The previous events.
981
+ """
982
+
983
+ # The set of event_ids to return. This includes all soft-failed events
984
+ # and their prev events.
985
+ existing_prevs: set[str] = set()
986
+
987
+ def _get_prevs_before_rejected_txn(
988
+ txn: LoggingTransaction, batch: Collection[str]
989
+ ) -> None:
990
+ to_recursively_check = batch
991
+
992
+ while to_recursively_check:
993
+ sql = """
994
+ SELECT
995
+ event_id, prev_event_id, internal_metadata,
996
+ rejections.event_id IS NOT NULL
997
+ FROM event_edges
998
+ INNER JOIN events USING (event_id)
999
+ LEFT JOIN rejections USING (event_id)
1000
+ LEFT JOIN event_json USING (event_id)
1001
+ WHERE
1002
+ NOT events.outlier
1003
+ AND
1004
+ """
1005
+
1006
+ clause, args = make_in_list_sql_clause(
1007
+ self.database_engine, "event_id", to_recursively_check
1008
+ )
1009
+
1010
+ txn.execute(sql + clause, args)
1011
+ to_recursively_check = []
1012
+
1013
+ for _, prev_event_id, metadata, rejected in txn:
1014
+ if prev_event_id in existing_prevs:
1015
+ continue
1016
+
1017
+ soft_failed = db_to_json(metadata).get("soft_failed")
1018
+ if soft_failed or rejected:
1019
+ to_recursively_check.append(prev_event_id)
1020
+ existing_prevs.add(prev_event_id)
1021
+
1022
+ for chunk in batch_iter(event_ids, 100):
1023
+ await self.db_pool.runInteraction(
1024
+ "_get_prevs_before_rejected", _get_prevs_before_rejected_txn, chunk
1025
+ )
1026
+
1027
+ return existing_prevs
1028
+
1029
+ def _persist_events_txn(
1030
+ self,
1031
+ txn: LoggingTransaction,
1032
+ *,
1033
+ room_id: str,
1034
+ events_and_contexts: list[EventPersistencePair],
1035
+ inhibit_local_membership_updates: bool,
1036
+ state_delta_for_room: DeltaState | None,
1037
+ new_forward_extremities: set[str] | None,
1038
+ new_event_links: dict[str, NewEventChainLinks],
1039
+ sliding_sync_table_changes: SlidingSyncTableChanges | None,
1040
+ ) -> None:
1041
+ """Insert some number of room events into the necessary database tables.
1042
+
1043
+ Rejected events are only inserted into the events table, the events_json table,
1044
+ and the rejections table. Things reading from those table will need to check
1045
+ whether the event was rejected.
1046
+
1047
+ Assumes that we are only persisting events for one room at a time.
1048
+
1049
+ Args:
1050
+ txn
1051
+ room_id: The room the events are from
1052
+ events_and_contexts: events to persist
1053
+ inhibit_local_membership_updates: Stop the local_current_membership
1054
+ from being updated by these events. This should be set to True
1055
+ for backfilled events because backfilled events in the past do
1056
+ not affect the current local state.
1057
+ delete_existing True to purge existing table rows for the events
1058
+ from the database. This is useful when retrying due to
1059
+ IntegrityError.
1060
+ state_delta_for_room: Deltas that are going to be used to update the
1061
+ `current_state_events` table. Changes to the current state of the room.
1062
+ new_forward_extremities: The new forward extremities for the room:
1063
+ a set of the event ids which are the forward extremities.
1064
+ sliding_sync_table_changes: Changes to the
1065
+ `sliding_sync_membership_snapshots` and `sliding_sync_joined_rooms` tables
1066
+ derived from the given `delta_state` (see
1067
+ `_calculate_sliding_sync_table_changes(...)`)
1068
+
1069
+ Raises:
1070
+ PartialStateConflictError: if attempting to persist a partial state event in
1071
+ a room that has been un-partial stated.
1072
+ """
1073
+ all_events_and_contexts = events_and_contexts
1074
+
1075
+ min_stream_order = events_and_contexts[0][0].internal_metadata.stream_ordering
1076
+ max_stream_order = events_and_contexts[-1][0].internal_metadata.stream_ordering
1077
+
1078
+ # We check that the room still exists for events we're trying to
1079
+ # persist. This is to protect against races with deleting a room.
1080
+ #
1081
+ # Annoyingly SQLite doesn't support row level locking.
1082
+ if isinstance(self.database_engine, PostgresEngine):
1083
+ txn.execute(
1084
+ "SELECT room_version FROM rooms WHERE room_id = ? FOR SHARE",
1085
+ (room_id,),
1086
+ )
1087
+ row = txn.fetchone()
1088
+ if row is None:
1089
+ raise Exception(f"Room does not exist {room_id}")
1090
+
1091
+ # stream orderings should have been assigned by now
1092
+ assert min_stream_order
1093
+ assert max_stream_order
1094
+
1095
+ # Once the txn completes, invalidate all of the relevant caches. Note that we do this
1096
+ # up here because it captures all the events_and_contexts before any are removed.
1097
+ for event, _ in events_and_contexts:
1098
+ self.store.invalidate_get_event_cache_after_txn(txn, event.event_id)
1099
+ if event.redacts:
1100
+ self.store.invalidate_get_event_cache_after_txn(txn, event.redacts)
1101
+
1102
+ relates_to = None
1103
+ relation = relation_from_event(event)
1104
+ if relation:
1105
+ relates_to = relation.parent_id
1106
+
1107
+ assert event.internal_metadata.stream_ordering is not None
1108
+ txn.call_after(
1109
+ self.store._invalidate_caches_for_event,
1110
+ event.internal_metadata.stream_ordering,
1111
+ event.event_id,
1112
+ event.room_id,
1113
+ event.type,
1114
+ getattr(event, "state_key", None),
1115
+ event.redacts,
1116
+ relates_to,
1117
+ backfilled=False,
1118
+ )
1119
+
1120
+ # Ensure that we don't have the same event twice.
1121
+ events_and_contexts = self._filter_events_and_contexts_for_duplicates(
1122
+ events_and_contexts
1123
+ )
1124
+
1125
+ self._update_room_depths_txn(
1126
+ txn, room_id, events_and_contexts=events_and_contexts
1127
+ )
1128
+
1129
+ # _update_outliers_txn filters out any events which have already been
1130
+ # persisted, and returns the filtered list.
1131
+ events_and_contexts = self._update_outliers_txn(
1132
+ txn, events_and_contexts=events_and_contexts
1133
+ )
1134
+
1135
+ # From this point onwards the events are only events that we haven't
1136
+ # seen before.
1137
+
1138
+ self._store_event_txn(txn, events_and_contexts=events_and_contexts)
1139
+
1140
+ if new_forward_extremities:
1141
+ self._update_forward_extremities_txn(
1142
+ txn,
1143
+ room_id,
1144
+ new_forward_extremities=new_forward_extremities,
1145
+ max_stream_order=max_stream_order,
1146
+ )
1147
+
1148
+ self._persist_transaction_ids_txn(txn, events_and_contexts)
1149
+
1150
+ # Insert into event_to_state_groups.
1151
+ self._store_event_state_mappings_txn(txn, events_and_contexts)
1152
+
1153
+ self._persist_event_auth_chain_txn(
1154
+ txn, [e for e, _ in events_and_contexts], new_event_links
1155
+ )
1156
+
1157
+ # _store_rejected_events_txn filters out any events which were
1158
+ # rejected, and returns the filtered list.
1159
+ events_and_contexts = self._store_rejected_events_txn(
1160
+ txn, events_and_contexts=events_and_contexts
1161
+ )
1162
+
1163
+ # From this point onwards the events are only ones that weren't
1164
+ # rejected.
1165
+
1166
+ self._update_metadata_tables_txn(
1167
+ txn,
1168
+ events_and_contexts=events_and_contexts,
1169
+ all_events_and_contexts=all_events_and_contexts,
1170
+ inhibit_local_membership_updates=inhibit_local_membership_updates,
1171
+ )
1172
+
1173
+ # We call this last as it assumes we've inserted the events into
1174
+ # room_memberships, where applicable.
1175
+ # NB: This function invalidates all state related caches
1176
+ if state_delta_for_room:
1177
+ # If the state delta exists, the sliding sync table changes should also exist
1178
+ assert sliding_sync_table_changes is not None
1179
+
1180
+ self._update_current_state_txn(
1181
+ txn,
1182
+ room_id,
1183
+ state_delta_for_room,
1184
+ min_stream_order,
1185
+ sliding_sync_table_changes,
1186
+ )
1187
+
1188
+ # We only update the sliding sync tables for non-backfilled events.
1189
+ self._update_sliding_sync_tables_with_new_persisted_events_txn(
1190
+ txn, room_id, events_and_contexts
1191
+ )
1192
+
1193
+ def _persist_event_auth_chain_txn(
1194
+ self,
1195
+ txn: LoggingTransaction,
1196
+ events: list[EventBase],
1197
+ new_event_links: dict[str, NewEventChainLinks],
1198
+ ) -> None:
1199
+ if new_event_links:
1200
+ self._persist_chain_cover_index(txn, self.db_pool, new_event_links)
1201
+
1202
+ # We only care about state events, so this if there are no state events.
1203
+ if not any(e.is_state() for e in events):
1204
+ return
1205
+
1206
+ # We want to store event_auth mappings for rejected events, as they're
1207
+ # used in state res v2.
1208
+ # This is only necessary if the rejected event appears in an accepted
1209
+ # event's auth chain, but its easier for now just to store them (and
1210
+ # it doesn't take much storage compared to storing the entire event
1211
+ # anyway).
1212
+ self.db_pool.simple_insert_many_txn(
1213
+ txn,
1214
+ table="event_auth",
1215
+ keys=("event_id", "room_id", "auth_id"),
1216
+ values=[
1217
+ (event.event_id, event.room_id, auth_id)
1218
+ for event in events
1219
+ for auth_id in event.auth_event_ids()
1220
+ if event.is_state()
1221
+ ],
1222
+ )
1223
+
1224
+ @classmethod
1225
+ def _add_chain_cover_index(
1226
+ cls,
1227
+ txn: LoggingTransaction,
1228
+ db_pool: DatabasePool,
1229
+ event_chain_id_gen: SequenceGenerator,
1230
+ event_to_room_id: dict[str, str],
1231
+ event_to_types: dict[str, tuple[str, str]],
1232
+ event_to_auth_chain: dict[str, StrCollection],
1233
+ ) -> None:
1234
+ """Calculate and persist the chain cover index for the given events.
1235
+
1236
+ Args:
1237
+ event_to_room_id: Event ID to the room ID of the event
1238
+ event_to_types: Event ID to type and state_key of the event
1239
+ event_to_auth_chain: Event ID to list of auth event IDs of the
1240
+ event (events with no auth events can be excluded).
1241
+ """
1242
+
1243
+ new_event_links = cls._calculate_chain_cover_index(
1244
+ txn,
1245
+ db_pool,
1246
+ event_chain_id_gen,
1247
+ event_to_room_id,
1248
+ event_to_types,
1249
+ event_to_auth_chain,
1250
+ )
1251
+ cls._persist_chain_cover_index(txn, db_pool, new_event_links)
1252
+
1253
+ @classmethod
1254
+ def _calculate_chain_cover_index(
1255
+ cls,
1256
+ txn: LoggingTransaction,
1257
+ db_pool: DatabasePool,
1258
+ event_chain_id_gen: SequenceGenerator,
1259
+ event_to_room_id: dict[str, str],
1260
+ event_to_types: dict[str, tuple[str, str]],
1261
+ event_to_auth_chain: dict[str, StrCollection],
1262
+ ) -> dict[str, NewEventChainLinks]:
1263
+ """Calculate the chain cover index for the given events.
1264
+
1265
+ Args:
1266
+ event_to_room_id: Event ID to the room ID of the event
1267
+ event_to_types: Event ID to type and state_key of the event
1268
+ event_to_auth_chain: Event ID to list of auth event IDs of the
1269
+ event (events with no auth events can be excluded).
1270
+
1271
+ Returns:
1272
+ A mapping with any new auth chain links we need to add, keyed by
1273
+ event ID.
1274
+ """
1275
+
1276
+ # Map from event ID to chain ID/sequence number.
1277
+ chain_map: dict[str, tuple[int, int]] = {}
1278
+
1279
+ # Set of event IDs to calculate chain ID/seq numbers for.
1280
+ events_to_calc_chain_id_for = set(event_to_room_id)
1281
+
1282
+ # We check if there are any events that need to be handled in the rooms
1283
+ # we're looking at. These should just be out of band memberships, where
1284
+ # we didn't have the auth chain when we first persisted.
1285
+ auth_chain_to_calc_rows = cast(
1286
+ list[tuple[str, str, str]],
1287
+ db_pool.simple_select_many_txn(
1288
+ txn,
1289
+ table="event_auth_chain_to_calculate",
1290
+ keyvalues={},
1291
+ column="room_id",
1292
+ iterable=set(event_to_room_id.values()),
1293
+ retcols=("event_id", "type", "state_key"),
1294
+ ),
1295
+ )
1296
+ for event_id, event_type, state_key in auth_chain_to_calc_rows:
1297
+ # (We could pull out the auth events for all rows at once using
1298
+ # simple_select_many, but this case happens rarely and almost always
1299
+ # with a single row.)
1300
+ auth_events = db_pool.simple_select_onecol_txn(
1301
+ txn,
1302
+ "event_auth",
1303
+ keyvalues={"event_id": event_id},
1304
+ retcol="auth_id",
1305
+ )
1306
+
1307
+ events_to_calc_chain_id_for.add(event_id)
1308
+ event_to_types[event_id] = (event_type, state_key)
1309
+ event_to_auth_chain[event_id] = auth_events
1310
+
1311
+ # First we get the chain ID and sequence numbers for the events'
1312
+ # auth events (that aren't also currently being persisted).
1313
+ #
1314
+ # Note that there there is an edge case here where we might not have
1315
+ # calculated chains and sequence numbers for events that were "out
1316
+ # of band". We handle this case by fetching the necessary info and
1317
+ # adding it to the set of events to calculate chain IDs for.
1318
+
1319
+ missing_auth_chains = {
1320
+ a_id
1321
+ for auth_events in event_to_auth_chain.values()
1322
+ for a_id in auth_events
1323
+ if a_id not in events_to_calc_chain_id_for
1324
+ }
1325
+
1326
+ # We loop here in case we find an out of band membership and need to
1327
+ # fetch their auth event info.
1328
+ while missing_auth_chains:
1329
+ sql = """
1330
+ SELECT event_id, events.type, se.state_key, chain_id, sequence_number
1331
+ FROM events
1332
+ INNER JOIN state_events AS se USING (event_id)
1333
+ LEFT JOIN event_auth_chains USING (event_id)
1334
+ WHERE
1335
+ """
1336
+ clause, args = make_in_list_sql_clause(
1337
+ txn.database_engine,
1338
+ "event_id",
1339
+ missing_auth_chains,
1340
+ )
1341
+ txn.execute(sql + clause, args)
1342
+
1343
+ missing_auth_chains.clear()
1344
+
1345
+ for (
1346
+ auth_id,
1347
+ event_type,
1348
+ state_key,
1349
+ chain_id,
1350
+ sequence_number,
1351
+ ) in txn.fetchall():
1352
+ event_to_types[auth_id] = (event_type, state_key)
1353
+
1354
+ if chain_id is None:
1355
+ # No chain ID, so the event was persisted out of band.
1356
+ # We add to list of events to calculate auth chains for.
1357
+
1358
+ events_to_calc_chain_id_for.add(auth_id)
1359
+
1360
+ event_to_auth_chain[auth_id] = db_pool.simple_select_onecol_txn(
1361
+ txn,
1362
+ "event_auth",
1363
+ keyvalues={"event_id": auth_id},
1364
+ retcol="auth_id",
1365
+ )
1366
+
1367
+ missing_auth_chains.update(
1368
+ e
1369
+ for e in event_to_auth_chain[auth_id]
1370
+ if e not in event_to_types
1371
+ )
1372
+ else:
1373
+ chain_map[auth_id] = (chain_id, sequence_number)
1374
+
1375
+ # Now we check if we have any events where we don't have auth chain,
1376
+ # this should only be out of band memberships.
1377
+ for event_id in sorted_topologically(event_to_auth_chain, event_to_auth_chain):
1378
+ for auth_id in event_to_auth_chain[event_id]:
1379
+ if (
1380
+ auth_id not in chain_map
1381
+ and auth_id not in events_to_calc_chain_id_for
1382
+ ):
1383
+ events_to_calc_chain_id_for.discard(event_id)
1384
+
1385
+ # If this is an event we're trying to persist we add it to
1386
+ # the list of events to calculate chain IDs for next time
1387
+ # around. (Otherwise we will have already added it to the
1388
+ # table).
1389
+ room_id = event_to_room_id.get(event_id)
1390
+ if room_id:
1391
+ e_type, state_key = event_to_types[event_id]
1392
+ db_pool.simple_upsert_txn(
1393
+ txn,
1394
+ table="event_auth_chain_to_calculate",
1395
+ keyvalues={"event_id": event_id},
1396
+ values={
1397
+ "room_id": room_id,
1398
+ "type": e_type,
1399
+ "state_key": state_key,
1400
+ },
1401
+ )
1402
+
1403
+ # We stop checking the event's auth events since we've
1404
+ # discarded it.
1405
+ break
1406
+
1407
+ if not events_to_calc_chain_id_for:
1408
+ return {}
1409
+
1410
+ # Allocate chain ID/sequence numbers to each new event.
1411
+ new_chain_tuples = cls._allocate_chain_ids(
1412
+ txn,
1413
+ db_pool,
1414
+ event_chain_id_gen,
1415
+ event_to_room_id,
1416
+ event_to_types,
1417
+ event_to_auth_chain,
1418
+ events_to_calc_chain_id_for,
1419
+ chain_map,
1420
+ )
1421
+ chain_map.update(new_chain_tuples)
1422
+
1423
+ to_return = {
1424
+ event_id: NewEventChainLinks(chain_id, sequence_number)
1425
+ for event_id, (chain_id, sequence_number) in new_chain_tuples.items()
1426
+ }
1427
+
1428
+ # Now we need to calculate any new links between chains caused by
1429
+ # the new events.
1430
+ #
1431
+ # Links are pairs of chain ID/sequence numbers such that for any
1432
+ # event A (CA, SA) and any event B (CB, SB), B is in A's auth chain
1433
+ # if and only if there is at least one link (CA, S1) -> (CB, S2)
1434
+ # where SA >= S1 and S2 >= SB.
1435
+ #
1436
+ # We try and avoid adding redundant links to the table, e.g. if we
1437
+ # have two links between two chains which both start/end at the
1438
+ # sequence number event (or cross) then one can be safely dropped.
1439
+ #
1440
+ # To calculate new links we look at every new event and:
1441
+ # 1. Fetch the chain ID/sequence numbers of its auth events,
1442
+ # discarding any that are reachable by other auth events, or
1443
+ # that have the same chain ID as the event.
1444
+ # 2. For each retained auth event we:
1445
+ # a. Add a link from the event's to the auth event's chain
1446
+ # ID/sequence number
1447
+
1448
+ # Step 1, fetch all existing links from all the chains we've seen
1449
+ # referenced.
1450
+ chain_links = _LinkMap()
1451
+
1452
+ for links in EventFederationStore._get_chain_links(
1453
+ txn, {chain_id for chain_id, _ in chain_map.values()}
1454
+ ):
1455
+ for origin_chain_id, inner_links in links.items():
1456
+ for (
1457
+ origin_sequence_number,
1458
+ target_chain_id,
1459
+ target_sequence_number,
1460
+ ) in inner_links:
1461
+ chain_links.add_link(
1462
+ (origin_chain_id, origin_sequence_number),
1463
+ (target_chain_id, target_sequence_number),
1464
+ new=False,
1465
+ )
1466
+
1467
+ # We do this in toplogical order to avoid adding redundant links.
1468
+ for event_id in sorted_topologically(
1469
+ events_to_calc_chain_id_for, event_to_auth_chain
1470
+ ):
1471
+ chain_id, sequence_number = chain_map[event_id]
1472
+
1473
+ # Filter out auth events that are reachable by other auth
1474
+ # events. We do this by looking at every permutation of pairs of
1475
+ # auth events (A, B) to check if B is reachable from A.
1476
+ reduction = {
1477
+ a_id
1478
+ for a_id in event_to_auth_chain.get(event_id, [])
1479
+ if chain_map[a_id][0] != chain_id
1480
+ }
1481
+ for start_auth_id, end_auth_id in itertools.permutations(
1482
+ event_to_auth_chain.get(event_id, []),
1483
+ r=2,
1484
+ ):
1485
+ if chain_links.exists_path_from(
1486
+ chain_map[start_auth_id], chain_map[end_auth_id]
1487
+ ):
1488
+ reduction.discard(end_auth_id)
1489
+
1490
+ # Step 2, figure out what the new links are from the reduced
1491
+ # list of auth events.
1492
+ for auth_id in reduction:
1493
+ auth_chain_id, auth_sequence_number = chain_map[auth_id]
1494
+
1495
+ # Step 2a, add link between the event and auth event
1496
+ to_return[event_id].links.append((auth_chain_id, auth_sequence_number))
1497
+ chain_links.add_link(
1498
+ (chain_id, sequence_number), (auth_chain_id, auth_sequence_number)
1499
+ )
1500
+
1501
+ return to_return
1502
+
1503
+ @classmethod
1504
+ def _persist_chain_cover_index(
1505
+ cls,
1506
+ txn: LoggingTransaction,
1507
+ db_pool: DatabasePool,
1508
+ new_event_links: dict[str, NewEventChainLinks],
1509
+ ) -> None:
1510
+ db_pool.simple_insert_many_txn(
1511
+ txn,
1512
+ table="event_auth_chains",
1513
+ keys=("event_id", "chain_id", "sequence_number"),
1514
+ values=[
1515
+ (event_id, new_links.chain_id, new_links.sequence_number)
1516
+ for event_id, new_links in new_event_links.items()
1517
+ ],
1518
+ )
1519
+
1520
+ db_pool.simple_delete_many_txn(
1521
+ txn,
1522
+ table="event_auth_chain_to_calculate",
1523
+ keyvalues={},
1524
+ column="event_id",
1525
+ values=new_event_links,
1526
+ )
1527
+
1528
+ db_pool.simple_insert_many_txn(
1529
+ txn,
1530
+ table="event_auth_chain_links",
1531
+ keys=(
1532
+ "origin_chain_id",
1533
+ "origin_sequence_number",
1534
+ "target_chain_id",
1535
+ "target_sequence_number",
1536
+ ),
1537
+ values=[
1538
+ (
1539
+ new_links.chain_id,
1540
+ new_links.sequence_number,
1541
+ target_chain_id,
1542
+ target_sequence_number,
1543
+ )
1544
+ for new_links in new_event_links.values()
1545
+ for (target_chain_id, target_sequence_number) in new_links.links
1546
+ ],
1547
+ )
1548
+
1549
+ @staticmethod
1550
+ def _allocate_chain_ids(
1551
+ txn: LoggingTransaction,
1552
+ db_pool: DatabasePool,
1553
+ event_chain_id_gen: SequenceGenerator,
1554
+ event_to_room_id: dict[str, str],
1555
+ event_to_types: dict[str, tuple[str, str]],
1556
+ event_to_auth_chain: dict[str, StrCollection],
1557
+ events_to_calc_chain_id_for: set[str],
1558
+ chain_map: dict[str, tuple[int, int]],
1559
+ ) -> dict[str, tuple[int, int]]:
1560
+ """Allocates, but does not persist, chain ID/sequence numbers for the
1561
+ events in `events_to_calc_chain_id_for`. (c.f. _add_chain_cover_index
1562
+ for info on args)
1563
+ """
1564
+
1565
+ # We now calculate the chain IDs/sequence numbers for the events. We do
1566
+ # this by looking at the chain ID and sequence number of any auth event
1567
+ # with the same type/state_key and incrementing the sequence number by
1568
+ # one. If there was no match or the chain ID/sequence number is already
1569
+ # taken we generate a new chain.
1570
+ #
1571
+ # We try to reduce the number of times that we hit the database by
1572
+ # batching up calls, to make this more efficient when persisting large
1573
+ # numbers of state events (e.g. during joins).
1574
+ #
1575
+ # We do this by:
1576
+ # 1. Calculating for each event which auth event will be used to
1577
+ # inherit the chain ID, i.e. converting the auth chain graph to a
1578
+ # tree that we can allocate chains on. We also keep track of which
1579
+ # existing chain IDs have been referenced.
1580
+ # 2. Fetching the max allocated sequence number for each referenced
1581
+ # existing chain ID, generating a map from chain ID to the max
1582
+ # allocated sequence number.
1583
+ # 3. Iterating over the tree and allocating a chain ID/seq no. to the
1584
+ # new event, by incrementing the sequence number from the
1585
+ # referenced event's chain ID/seq no. and checking that the
1586
+ # incremented sequence number hasn't already been allocated (by
1587
+ # looking in the map generated in the previous step). We generate a
1588
+ # new chain if the sequence number has already been allocated.
1589
+ #
1590
+
1591
+ existing_chains: set[int] = set()
1592
+ tree: list[tuple[str, str | None]] = []
1593
+
1594
+ # We need to do this in a topologically sorted order as we want to
1595
+ # generate chain IDs/sequence numbers of an event's auth events before
1596
+ # the event itself.
1597
+ for event_id in sorted_topologically(
1598
+ events_to_calc_chain_id_for, event_to_auth_chain
1599
+ ):
1600
+ for auth_id in event_to_auth_chain.get(event_id, []):
1601
+ if event_to_types.get(event_id) == event_to_types.get(auth_id):
1602
+ existing_chain_id = chain_map.get(auth_id)
1603
+ if existing_chain_id:
1604
+ existing_chains.add(existing_chain_id[0])
1605
+
1606
+ tree.append((event_id, auth_id))
1607
+ break
1608
+ else:
1609
+ tree.append((event_id, None))
1610
+
1611
+ # Fetch the current max sequence number for each existing referenced chain.
1612
+ sql = """
1613
+ SELECT chain_id, MAX(sequence_number) FROM event_auth_chains
1614
+ WHERE %s
1615
+ GROUP BY chain_id
1616
+ """
1617
+ clause, args = make_in_list_sql_clause(
1618
+ db_pool.engine, "chain_id", existing_chains
1619
+ )
1620
+ txn.execute(sql % (clause,), args)
1621
+
1622
+ chain_to_max_seq_no: dict[Any, int] = {row[0]: row[1] for row in txn}
1623
+
1624
+ # Allocate the new events chain ID/sequence numbers.
1625
+ #
1626
+ # To reduce the number of calls to the database we don't allocate a
1627
+ # chain ID number in the loop, instead we use a temporary `object()` for
1628
+ # each new chain ID. Once we've done the loop we generate the necessary
1629
+ # number of new chain IDs in one call, replacing all temporary
1630
+ # objects with real allocated chain IDs.
1631
+
1632
+ unallocated_chain_ids: set[object] = set()
1633
+ new_chain_tuples: dict[str, tuple[Any, int]] = {}
1634
+ for event_id, auth_event_id in tree:
1635
+ # If we reference an auth_event_id we fetch the allocated chain ID,
1636
+ # either from the existing `chain_map` or the newly generated
1637
+ # `new_chain_tuples` map.
1638
+ existing_chain_id = None
1639
+ if auth_event_id:
1640
+ existing_chain_id = new_chain_tuples.get(auth_event_id)
1641
+ if not existing_chain_id:
1642
+ existing_chain_id = chain_map[auth_event_id]
1643
+
1644
+ new_chain_tuple: tuple[Any, int] | None = None
1645
+ if existing_chain_id:
1646
+ # We found a chain ID/sequence number candidate, check its
1647
+ # not already taken.
1648
+ proposed_new_id = existing_chain_id[0]
1649
+ proposed_new_seq = existing_chain_id[1] + 1
1650
+
1651
+ if chain_to_max_seq_no[proposed_new_id] < proposed_new_seq:
1652
+ new_chain_tuple = (
1653
+ proposed_new_id,
1654
+ proposed_new_seq,
1655
+ )
1656
+
1657
+ # If we need to start a new chain we allocate a temporary chain ID.
1658
+ if not new_chain_tuple:
1659
+ new_chain_tuple = (object(), 1)
1660
+ unallocated_chain_ids.add(new_chain_tuple[0])
1661
+
1662
+ new_chain_tuples[event_id] = new_chain_tuple
1663
+ chain_to_max_seq_no[new_chain_tuple[0]] = new_chain_tuple[1]
1664
+
1665
+ # Generate new chain IDs for all unallocated chain IDs.
1666
+ newly_allocated_chain_ids = event_chain_id_gen.get_next_mult_txn(
1667
+ txn, len(unallocated_chain_ids)
1668
+ )
1669
+
1670
+ # Map from potentially temporary chain ID to real chain ID
1671
+ chain_id_to_allocated_map: dict[Any, int] = dict(
1672
+ zip(unallocated_chain_ids, newly_allocated_chain_ids)
1673
+ )
1674
+ chain_id_to_allocated_map.update((c, c) for c in existing_chains)
1675
+
1676
+ return {
1677
+ event_id: (chain_id_to_allocated_map[chain_id], seq)
1678
+ for event_id, (chain_id, seq) in new_chain_tuples.items()
1679
+ }
1680
+
1681
+ def _persist_transaction_ids_txn(
1682
+ self,
1683
+ txn: LoggingTransaction,
1684
+ events_and_contexts: list[EventPersistencePair],
1685
+ ) -> None:
1686
+ """Persist the mapping from transaction IDs to event IDs (if defined)."""
1687
+
1688
+ inserted_ts = self._clock.time_msec()
1689
+ to_insert_device_id: list[tuple[str, str, str, str, str, int]] = []
1690
+ for event, _ in events_and_contexts:
1691
+ txn_id = getattr(event.internal_metadata, "txn_id", None)
1692
+ device_id = getattr(event.internal_metadata, "device_id", None)
1693
+
1694
+ if txn_id is not None:
1695
+ if device_id is not None:
1696
+ to_insert_device_id.append(
1697
+ (
1698
+ event.event_id,
1699
+ event.room_id,
1700
+ event.sender,
1701
+ device_id,
1702
+ txn_id,
1703
+ inserted_ts,
1704
+ )
1705
+ )
1706
+
1707
+ # Synapse relies on the device_id to scope transactions for events..
1708
+ if to_insert_device_id:
1709
+ self.db_pool.simple_insert_many_txn(
1710
+ txn,
1711
+ table="event_txn_id_device_id",
1712
+ keys=(
1713
+ "event_id",
1714
+ "room_id",
1715
+ "user_id",
1716
+ "device_id",
1717
+ "txn_id",
1718
+ "inserted_ts",
1719
+ ),
1720
+ values=to_insert_device_id,
1721
+ )
1722
+
1723
+ async def update_current_state(
1724
+ self,
1725
+ room_id: str,
1726
+ state_delta: DeltaState,
1727
+ sliding_sync_table_changes: SlidingSyncTableChanges,
1728
+ ) -> None:
1729
+ """
1730
+ Update the current state stored in the datatabase for the given room
1731
+
1732
+ Args:
1733
+ room_id
1734
+ state_delta: Deltas that are going to be used to update the
1735
+ `current_state_events` table. Changes to the current state of the room.
1736
+ sliding_sync_table_changes: Changes to the
1737
+ `sliding_sync_membership_snapshots` and `sliding_sync_joined_rooms` tables
1738
+ derived from the given `delta_state` (see
1739
+ `_calculate_sliding_sync_table_changes(...)`)
1740
+ """
1741
+
1742
+ if state_delta.is_noop():
1743
+ return
1744
+
1745
+ async with self._stream_id_gen.get_next() as stream_ordering:
1746
+ await self.db_pool.runInteraction(
1747
+ "update_current_state",
1748
+ self._update_current_state_txn,
1749
+ room_id,
1750
+ delta_state=state_delta,
1751
+ stream_id=stream_ordering,
1752
+ sliding_sync_table_changes=sliding_sync_table_changes,
1753
+ )
1754
+
1755
+ def _update_current_state_txn(
1756
+ self,
1757
+ txn: LoggingTransaction,
1758
+ room_id: str,
1759
+ delta_state: DeltaState,
1760
+ stream_id: int,
1761
+ sliding_sync_table_changes: SlidingSyncTableChanges,
1762
+ ) -> None:
1763
+ """
1764
+ Handles updating tables that track the current state of a room.
1765
+
1766
+ Args:
1767
+ txn
1768
+ room_id
1769
+ delta_state: Deltas that are going to be used to update the
1770
+ `current_state_events` table. Changes to the current state of the room.
1771
+ stream_id: This is expected to be the minimum `stream_ordering` for the
1772
+ batch of events that we are persisting; which means we do not end up in a
1773
+ situation where workers see events before the `current_state_delta` updates.
1774
+ FIXME: However, this function also gets called with next upcoming
1775
+ `stream_ordering` when we re-sync the state of a partial stated room (see
1776
+ `update_current_state(...)`) which may be "correct" but it would be good to
1777
+ nail down what exactly is the expected value here.
1778
+ sliding_sync_table_changes: Changes to the
1779
+ `sliding_sync_membership_snapshots` and `sliding_sync_joined_rooms` tables
1780
+ derived from the given `delta_state` (see
1781
+ `_calculate_sliding_sync_table_changes(...)`)
1782
+ """
1783
+ to_delete = delta_state.to_delete
1784
+ to_insert = delta_state.to_insert
1785
+
1786
+ # Sanity check we're processing the same thing
1787
+ assert room_id == sliding_sync_table_changes.room_id
1788
+
1789
+ # Figure out the changes of membership to invalidate the
1790
+ # `get_rooms_for_user` cache.
1791
+ # We find out which membership events we may have deleted
1792
+ # and which we have added, then we invalidate the caches for all
1793
+ # those users.
1794
+ members_to_cache_bust = {
1795
+ state_key
1796
+ for ev_type, state_key in itertools.chain(to_delete, to_insert)
1797
+ if ev_type == EventTypes.Member
1798
+ }
1799
+
1800
+ if delta_state.no_longer_in_room:
1801
+ # Server is no longer in the room so we delete the room from
1802
+ # current_state_events, being careful we've already updated the
1803
+ # rooms.room_version column (which gets populated in a
1804
+ # background task).
1805
+ self._upsert_room_version_txn(txn, room_id)
1806
+
1807
+ # Before deleting we populate the current_state_delta_stream
1808
+ # so that async background tasks get told what happened.
1809
+ sql = """
1810
+ INSERT INTO current_state_delta_stream
1811
+ (stream_id, instance_name, room_id, type, state_key, event_id, prev_event_id)
1812
+ SELECT ?, ?, room_id, type, state_key, null, event_id
1813
+ FROM current_state_events
1814
+ WHERE room_id = ?
1815
+ """
1816
+ txn.execute(sql, (stream_id, self._instance_name, room_id))
1817
+
1818
+ # Grab the list of users before we clear out the current state
1819
+ users_in_room = self.store.get_users_in_room_txn(txn, room_id)
1820
+ # We also want to invalidate the membership caches for users
1821
+ # that were in the room.
1822
+ members_to_cache_bust.update(users_in_room)
1823
+
1824
+ self.db_pool.simple_delete_txn(
1825
+ txn,
1826
+ table="current_state_events",
1827
+ keyvalues={"room_id": room_id},
1828
+ )
1829
+ self.db_pool.simple_delete_txn(
1830
+ txn,
1831
+ table="sliding_sync_joined_rooms",
1832
+ keyvalues={"room_id": room_id},
1833
+ )
1834
+ else:
1835
+ # We're still in the room, so we update the current state as normal.
1836
+
1837
+ # First we add entries to the current_state_delta_stream. We
1838
+ # do this before updating the current_state_events table so
1839
+ # that we can use it to calculate the `prev_event_id`. (This
1840
+ # allows us to not have to pull out the existing state
1841
+ # unnecessarily).
1842
+ #
1843
+ # The stream_id for the update is chosen to be the minimum of the stream_ids
1844
+ # for the batch of the events that we are persisting; that means we do not
1845
+ # end up in a situation where workers see events before the
1846
+ # current_state_delta updates.
1847
+ #
1848
+ sql = """
1849
+ INSERT INTO current_state_delta_stream
1850
+ (stream_id, instance_name, room_id, type, state_key, event_id, prev_event_id)
1851
+ SELECT ?, ?, ?, ?, ?, ?, (
1852
+ SELECT event_id FROM current_state_events
1853
+ WHERE room_id = ? AND type = ? AND state_key = ?
1854
+ )
1855
+ """
1856
+ txn.execute_batch(
1857
+ sql,
1858
+ [
1859
+ (
1860
+ stream_id,
1861
+ self._instance_name,
1862
+ room_id,
1863
+ etype,
1864
+ state_key,
1865
+ to_insert.get((etype, state_key)),
1866
+ room_id,
1867
+ etype,
1868
+ state_key,
1869
+ )
1870
+ for etype, state_key in itertools.chain(to_delete, to_insert)
1871
+ ],
1872
+ )
1873
+ # Now we actually update the current_state_events table
1874
+
1875
+ txn.execute_batch(
1876
+ "DELETE FROM current_state_events"
1877
+ " WHERE room_id = ? AND type = ? AND state_key = ?",
1878
+ [
1879
+ (room_id, etype, state_key)
1880
+ for etype, state_key in itertools.chain(to_delete, to_insert)
1881
+ ],
1882
+ )
1883
+
1884
+ # We include the membership in the current state table, hence we do
1885
+ # a lookup when we insert. This assumes that all events have already
1886
+ # been inserted into room_memberships.
1887
+ txn.execute_batch(
1888
+ """INSERT INTO current_state_events
1889
+ (room_id, type, state_key, event_id, membership, event_stream_ordering)
1890
+ VALUES (
1891
+ ?, ?, ?, ?,
1892
+ (SELECT membership FROM room_memberships WHERE event_id = ?),
1893
+ (SELECT stream_ordering FROM events WHERE event_id = ?)
1894
+ )
1895
+ """,
1896
+ [
1897
+ (room_id, key[0], key[1], ev_id, ev_id, ev_id)
1898
+ for key, ev_id in to_insert.items()
1899
+ ],
1900
+ )
1901
+
1902
+ # Handle updating the `sliding_sync_joined_rooms` table. We only deal with
1903
+ # updating the state related columns. The
1904
+ # `event_stream_ordering`/`bump_stamp` are updated elsewhere in the event
1905
+ # persisting stack (see
1906
+ # `_update_sliding_sync_tables_with_new_persisted_events_txn()`)
1907
+ #
1908
+ # We only need to update when one of the relevant state values has changed
1909
+ if sliding_sync_table_changes.joined_room_updates:
1910
+ sliding_sync_updates_keys = (
1911
+ sliding_sync_table_changes.joined_room_updates.keys()
1912
+ )
1913
+ sliding_sync_updates_values = (
1914
+ sliding_sync_table_changes.joined_room_updates.values()
1915
+ )
1916
+
1917
+ args: list[Any] = [
1918
+ room_id,
1919
+ room_id,
1920
+ sliding_sync_table_changes.joined_room_bump_stamp_to_fully_insert,
1921
+ ]
1922
+ args.extend(iter(sliding_sync_updates_values))
1923
+
1924
+ # XXX: We use a sub-query for `stream_ordering` because it's unreliable to
1925
+ # pre-calculate from `events_and_contexts` at the time when
1926
+ # `_calculate_sliding_sync_table_changes()` is ran. We could be working
1927
+ # with events that were previously persisted as an `outlier` with one
1928
+ # `stream_ordering` but are now being persisted again and de-outliered
1929
+ # and assigned a different `stream_ordering`. Since we call
1930
+ # `_calculate_sliding_sync_table_changes()` before
1931
+ # `_update_outliers_txn()` which fixes this discrepancy (always use the
1932
+ # `stream_ordering` from the first time it was persisted), we're working
1933
+ # with an unreliable `stream_ordering` value that will possibly be
1934
+ # unused and not make it into the `events` table.
1935
+ #
1936
+ # We don't update `event_stream_ordering` `ON CONFLICT` because it's
1937
+ # simpler and we can just rely on
1938
+ # `_update_sliding_sync_tables_with_new_persisted_events_txn()` to do
1939
+ # the right thing (same for `bump_stamp`). The only reason we're
1940
+ # inserting `event_stream_ordering` here is because the column has a
1941
+ # `NON NULL` constraint and we need some answer.
1942
+ txn.execute(
1943
+ f"""
1944
+ INSERT INTO sliding_sync_joined_rooms
1945
+ (room_id, event_stream_ordering, bump_stamp, {", ".join(sliding_sync_updates_keys)})
1946
+ VALUES (
1947
+ ?,
1948
+ (SELECT stream_ordering FROM events WHERE room_id = ? ORDER BY stream_ordering DESC LIMIT 1),
1949
+ ?,
1950
+ {", ".join("?" for _ in sliding_sync_updates_values)}
1951
+ )
1952
+ ON CONFLICT (room_id)
1953
+ DO UPDATE SET
1954
+ {", ".join(f"{key} = EXCLUDED.{key}" for key in sliding_sync_updates_keys)}
1955
+ """,
1956
+ args,
1957
+ )
1958
+
1959
+ # We now update `local_current_membership`. We do this regardless
1960
+ # of whether we're still in the room or not to handle the case where
1961
+ # e.g. we just got banned (where we need to record that fact here).
1962
+
1963
+ # Note: Do we really want to delete rows here (that we do not
1964
+ # subsequently reinsert below)? While technically correct it means
1965
+ # we have no record of the fact the user *was* a member of the
1966
+ # room but got, say, state reset out of it.
1967
+ if to_delete or to_insert:
1968
+ txn.execute_batch(
1969
+ "DELETE FROM local_current_membership"
1970
+ " WHERE room_id = ? AND user_id = ?",
1971
+ [
1972
+ (room_id, state_key)
1973
+ for etype, state_key in itertools.chain(to_delete, to_insert)
1974
+ if etype == EventTypes.Member and self.is_mine_id(state_key)
1975
+ ],
1976
+ )
1977
+
1978
+ if to_insert:
1979
+ txn.execute_batch(
1980
+ """INSERT INTO local_current_membership
1981
+ (room_id, user_id, event_id, membership, event_stream_ordering)
1982
+ VALUES (
1983
+ ?, ?, ?,
1984
+ (SELECT membership FROM room_memberships WHERE event_id = ?),
1985
+ (SELECT stream_ordering FROM events WHERE event_id = ?)
1986
+ )
1987
+ """,
1988
+ [
1989
+ (room_id, key[1], ev_id, ev_id, ev_id)
1990
+ for key, ev_id in to_insert.items()
1991
+ if key[0] == EventTypes.Member and self.is_mine_id(key[1])
1992
+ ],
1993
+ )
1994
+
1995
+ # Handle updating the `sliding_sync_membership_snapshots` table
1996
+ #
1997
+ # This would only happen if someone was state reset out of the room
1998
+ if sliding_sync_table_changes.to_delete_membership_snapshots:
1999
+ self.db_pool.simple_delete_many_txn(
2000
+ txn,
2001
+ table="sliding_sync_membership_snapshots",
2002
+ column="user_id",
2003
+ values=sliding_sync_table_changes.to_delete_membership_snapshots,
2004
+ keyvalues={"room_id": room_id},
2005
+ )
2006
+
2007
+ # We do this regardless of whether the server is `no_longer_in_room` or not
2008
+ # because we still want a row if a local user was just left/kicked or got banned
2009
+ # from the room.
2010
+ if sliding_sync_table_changes.to_insert_membership_snapshots:
2011
+ # Update the `sliding_sync_membership_snapshots` table
2012
+ #
2013
+ sliding_sync_snapshot_keys = sliding_sync_table_changes.membership_snapshot_shared_insert_values.keys()
2014
+ sliding_sync_snapshot_values = sliding_sync_table_changes.membership_snapshot_shared_insert_values.values()
2015
+ # We need to insert/update regardless of whether we have
2016
+ # `sliding_sync_snapshot_keys` because there are other fields in the `ON
2017
+ # CONFLICT` upsert to run (see inherit case (explained in
2018
+ # `_calculate_sliding_sync_table_changes()`) for more context when this
2019
+ # happens).
2020
+ #
2021
+ # XXX: We use a sub-query for `stream_ordering` because it's unreliable to
2022
+ # pre-calculate from `events_and_contexts` at the time when
2023
+ # `_calculate_sliding_sync_table_changes()` is ran. We could be working with
2024
+ # events that were previously persisted as an `outlier` with one
2025
+ # `stream_ordering` but are now being persisted again and de-outliered and
2026
+ # assigned a different `stream_ordering` that won't end up being used. Since
2027
+ # we call `_calculate_sliding_sync_table_changes()` before
2028
+ # `_update_outliers_txn()` which fixes this discrepancy (always use the
2029
+ # `stream_ordering` from the first time it was persisted), we're working
2030
+ # with an unreliable `stream_ordering` value that will possibly be unused
2031
+ # and not make it into the `events` table.
2032
+ txn.execute_batch(
2033
+ f"""
2034
+ INSERT INTO sliding_sync_membership_snapshots
2035
+ (room_id, user_id, sender, membership_event_id, membership, forgotten, event_stream_ordering, event_instance_name
2036
+ {("," + ", ".join(sliding_sync_snapshot_keys)) if sliding_sync_snapshot_keys else ""})
2037
+ VALUES (
2038
+ ?, ?, ?, ?, ?, ?,
2039
+ (SELECT stream_ordering FROM events WHERE event_id = ?),
2040
+ (SELECT COALESCE(instance_name, 'master') FROM events WHERE event_id = ?)
2041
+ {("," + ", ".join("?" for _ in sliding_sync_snapshot_values)) if sliding_sync_snapshot_values else ""}
2042
+ )
2043
+ ON CONFLICT (room_id, user_id)
2044
+ DO UPDATE SET
2045
+ sender = EXCLUDED.sender,
2046
+ membership_event_id = EXCLUDED.membership_event_id,
2047
+ membership = EXCLUDED.membership,
2048
+ forgotten = EXCLUDED.forgotten,
2049
+ event_stream_ordering = EXCLUDED.event_stream_ordering
2050
+ {("," + ", ".join(f"{key} = EXCLUDED.{key}" for key in sliding_sync_snapshot_keys)) if sliding_sync_snapshot_keys else ""}
2051
+ """,
2052
+ [
2053
+ [
2054
+ room_id,
2055
+ membership_info.user_id,
2056
+ membership_info.sender,
2057
+ membership_info.membership_event_id,
2058
+ membership_info.membership,
2059
+ # Since this is a new membership, it isn't forgotten anymore (which
2060
+ # matches how Synapse currently thinks about the forgotten status)
2061
+ 0,
2062
+ # XXX: We do not use `membership_info.membership_event_stream_ordering` here
2063
+ # because it is an unreliable value. See XXX note above.
2064
+ membership_info.membership_event_id,
2065
+ # XXX: We do not use `membership_info.membership_event_instance_name` here
2066
+ # because it is an unreliable value. See XXX note above.
2067
+ membership_info.membership_event_id,
2068
+ ]
2069
+ + list(sliding_sync_snapshot_values)
2070
+ for membership_info in sliding_sync_table_changes.to_insert_membership_snapshots
2071
+ ],
2072
+ )
2073
+
2074
+ txn.call_after(
2075
+ self.store._curr_state_delta_stream_cache.entity_has_changed,
2076
+ room_id,
2077
+ stream_id,
2078
+ )
2079
+
2080
+ for user_id in members_to_cache_bust:
2081
+ txn.call_after(
2082
+ self.store._membership_stream_cache.entity_has_changed,
2083
+ user_id,
2084
+ stream_id,
2085
+ )
2086
+
2087
+ # Invalidate the various caches
2088
+ self.store._invalidate_state_caches_and_stream(
2089
+ txn, room_id, members_to_cache_bust
2090
+ )
2091
+
2092
+ # Check if any of the remote membership changes requires us to
2093
+ # unsubscribe from their device lists.
2094
+ self.store.handle_potentially_left_users_txn(
2095
+ txn, {m for m in members_to_cache_bust if not self.hs.is_mine_id(m)}
2096
+ )
2097
+
2098
+ @classmethod
2099
+ def _get_relevant_sliding_sync_current_state_event_ids_txn(
2100
+ cls, txn: LoggingTransaction, room_id: str
2101
+ ) -> MutableStateMap[str]:
2102
+ """
2103
+ Fetch the current state event IDs for the relevant (to the
2104
+ `sliding_sync_joined_rooms` table) state types for the given room.
2105
+
2106
+ Returns:
2107
+ A tuple of:
2108
+ 1. StateMap of event IDs necessary to to fetch the relevant state values
2109
+ needed to insert into the
2110
+ `sliding_sync_joined_rooms`/`sliding_sync_membership_snapshots`.
2111
+ 2. The corresponding latest `stream_id` in the
2112
+ `current_state_delta_stream` table. This is useful to compare against
2113
+ the `current_state_delta_stream` table later so you can check whether
2114
+ the current state has changed since you last fetched the current
2115
+ state.
2116
+ """
2117
+ # Fetch the current state event IDs from the database
2118
+ (
2119
+ event_type_and_state_key_in_list_clause,
2120
+ event_type_and_state_key_args,
2121
+ ) = make_tuple_in_list_sql_clause(
2122
+ txn.database_engine,
2123
+ ("type", "state_key"),
2124
+ SLIDING_SYNC_RELEVANT_STATE_SET,
2125
+ )
2126
+ txn.execute(
2127
+ f"""
2128
+ SELECT c.event_id, c.type, c.state_key
2129
+ FROM current_state_events AS c
2130
+ WHERE
2131
+ c.room_id = ?
2132
+ AND {event_type_and_state_key_in_list_clause}
2133
+ """,
2134
+ [room_id] + event_type_and_state_key_args,
2135
+ )
2136
+ current_state_map: MutableStateMap[str] = {
2137
+ (event_type, state_key): event_id for event_id, event_type, state_key in txn
2138
+ }
2139
+
2140
+ return current_state_map
2141
+
2142
+ @classmethod
2143
+ def _get_sliding_sync_insert_values_from_state_map(
2144
+ cls, state_map: StateMap[EventBase]
2145
+ ) -> SlidingSyncStateInsertValues:
2146
+ """
2147
+ Extract the relevant state values from the `state_map` needed to insert into the
2148
+ `sliding_sync_joined_rooms`/`sliding_sync_membership_snapshots` tables.
2149
+
2150
+ Returns:
2151
+ Map from column names (`room_type`, `is_encrypted`, `room_name`) to relevant
2152
+ state values needed to insert into
2153
+ the `sliding_sync_joined_rooms`/`sliding_sync_membership_snapshots` tables.
2154
+ """
2155
+ # Map of values to insert/update in the `sliding_sync_membership_snapshots` table
2156
+ sliding_sync_insert_map: SlidingSyncStateInsertValues = {}
2157
+
2158
+ # Parse the raw event JSON
2159
+ for state_key, event in state_map.items():
2160
+ if state_key == (EventTypes.Create, ""):
2161
+ room_type = event.content.get(EventContentFields.ROOM_TYPE)
2162
+ # Scrutinize JSON values
2163
+ if room_type is None or (
2164
+ isinstance(room_type, str)
2165
+ # We ignore values with null bytes as Postgres doesn't allow them in
2166
+ # text columns.
2167
+ and "\0" not in room_type
2168
+ ):
2169
+ sliding_sync_insert_map["room_type"] = room_type
2170
+ elif state_key == (EventTypes.RoomEncryption, ""):
2171
+ encryption_algorithm = event.content.get(
2172
+ EventContentFields.ENCRYPTION_ALGORITHM
2173
+ )
2174
+ is_encrypted = encryption_algorithm is not None
2175
+ sliding_sync_insert_map["is_encrypted"] = is_encrypted
2176
+ elif state_key == (EventTypes.Name, ""):
2177
+ room_name = event.content.get(EventContentFields.ROOM_NAME)
2178
+ # Scrutinize JSON values. We ignore values with nulls as
2179
+ # postgres doesn't allow null bytes in text columns.
2180
+ if room_name is None or (
2181
+ isinstance(room_name, str)
2182
+ # We ignore values with null bytes as Postgres doesn't allow them in
2183
+ # text columns.
2184
+ and "\0" not in room_name
2185
+ ):
2186
+ sliding_sync_insert_map["room_name"] = room_name
2187
+ elif state_key == (EventTypes.Tombstone, ""):
2188
+ successor_room_id = event.content.get(
2189
+ EventContentFields.TOMBSTONE_SUCCESSOR_ROOM
2190
+ )
2191
+ # Scrutinize JSON values
2192
+ if successor_room_id is None or (
2193
+ isinstance(successor_room_id, str)
2194
+ # We ignore values with null bytes as Postgres doesn't allow them in
2195
+ # text columns.
2196
+ and "\0" not in successor_room_id
2197
+ ):
2198
+ sliding_sync_insert_map["tombstone_successor_room_id"] = (
2199
+ successor_room_id
2200
+ )
2201
+ else:
2202
+ # We only expect to see events according to the
2203
+ # `SLIDING_SYNC_RELEVANT_STATE_SET`.
2204
+ raise AssertionError(
2205
+ "Unexpected event (we should not be fetching extra events or this "
2206
+ + "piece of code needs to be updated to handle a new event type added "
2207
+ + "to `SLIDING_SYNC_RELEVANT_STATE_SET`): {state_key} {event.event_id}"
2208
+ )
2209
+
2210
+ return sliding_sync_insert_map
2211
+
2212
+ @classmethod
2213
+ def _get_sliding_sync_insert_values_from_stripped_state(
2214
+ cls, unsigned_stripped_state_events: Any
2215
+ ) -> SlidingSyncMembershipSnapshotSharedInsertValues:
2216
+ """
2217
+ Pull out the relevant state values from the stripped state on an invite or knock
2218
+ membership event needed to insert into the `sliding_sync_membership_snapshots`
2219
+ tables.
2220
+
2221
+ Returns:
2222
+ Map from column names (`room_type`, `is_encrypted`, `room_name`) to relevant
2223
+ state values needed to insert into the `sliding_sync_membership_snapshots` tables.
2224
+ """
2225
+ # Map of values to insert/update in the `sliding_sync_membership_snapshots` table
2226
+ sliding_sync_insert_map: SlidingSyncMembershipSnapshotSharedInsertValues = {}
2227
+
2228
+ if unsigned_stripped_state_events is not None:
2229
+ stripped_state_map: MutableStateMap[StrippedStateEvent] = {}
2230
+ if isinstance(unsigned_stripped_state_events, list):
2231
+ for raw_stripped_event in unsigned_stripped_state_events:
2232
+ stripped_state_event = parse_stripped_state_event(
2233
+ raw_stripped_event
2234
+ )
2235
+ if stripped_state_event is not None:
2236
+ stripped_state_map[
2237
+ (
2238
+ stripped_state_event.type,
2239
+ stripped_state_event.state_key,
2240
+ )
2241
+ ] = stripped_state_event
2242
+
2243
+ # If there is some stripped state, we assume the remote server passed *all*
2244
+ # of the potential stripped state events for the room.
2245
+ create_stripped_event = stripped_state_map.get((EventTypes.Create, ""))
2246
+ # Sanity check that we at-least have the create event
2247
+ if create_stripped_event is not None:
2248
+ sliding_sync_insert_map["has_known_state"] = True
2249
+
2250
+ # XXX: Keep this up-to-date with `SLIDING_SYNC_RELEVANT_STATE_SET`
2251
+
2252
+ # Find the room_type
2253
+ sliding_sync_insert_map["room_type"] = (
2254
+ create_stripped_event.content.get(EventContentFields.ROOM_TYPE)
2255
+ if create_stripped_event is not None
2256
+ else None
2257
+ )
2258
+
2259
+ # Find whether the room is_encrypted
2260
+ encryption_stripped_event = stripped_state_map.get(
2261
+ (EventTypes.RoomEncryption, "")
2262
+ )
2263
+ encryption = (
2264
+ encryption_stripped_event.content.get(
2265
+ EventContentFields.ENCRYPTION_ALGORITHM
2266
+ )
2267
+ if encryption_stripped_event is not None
2268
+ else None
2269
+ )
2270
+ sliding_sync_insert_map["is_encrypted"] = encryption is not None
2271
+
2272
+ # Find the room_name
2273
+ room_name_stripped_event = stripped_state_map.get((EventTypes.Name, ""))
2274
+ sliding_sync_insert_map["room_name"] = (
2275
+ room_name_stripped_event.content.get(EventContentFields.ROOM_NAME)
2276
+ if room_name_stripped_event is not None
2277
+ else None
2278
+ )
2279
+
2280
+ # Check for null bytes in the room name and type. We have to
2281
+ # ignore values with null bytes as Postgres doesn't allow them
2282
+ # in text columns.
2283
+ if (
2284
+ sliding_sync_insert_map["room_name"] is not None
2285
+ and "\0" in sliding_sync_insert_map["room_name"]
2286
+ ):
2287
+ sliding_sync_insert_map.pop("room_name")
2288
+
2289
+ if (
2290
+ sliding_sync_insert_map["room_type"] is not None
2291
+ and "\0" in sliding_sync_insert_map["room_type"]
2292
+ ):
2293
+ sliding_sync_insert_map.pop("room_type")
2294
+
2295
+ # Find the tombstone_successor_room_id
2296
+ # Note: This isn't one of the stripped state events according to the spec
2297
+ # but seems like there is no reason not to support this kind of thing.
2298
+ tombstone_stripped_event = stripped_state_map.get(
2299
+ (EventTypes.Tombstone, "")
2300
+ )
2301
+ sliding_sync_insert_map["tombstone_successor_room_id"] = (
2302
+ tombstone_stripped_event.content.get(
2303
+ EventContentFields.TOMBSTONE_SUCCESSOR_ROOM
2304
+ )
2305
+ if tombstone_stripped_event is not None
2306
+ else None
2307
+ )
2308
+
2309
+ if (
2310
+ sliding_sync_insert_map["tombstone_successor_room_id"] is not None
2311
+ and "\0" in sliding_sync_insert_map["tombstone_successor_room_id"]
2312
+ ):
2313
+ sliding_sync_insert_map.pop("tombstone_successor_room_id")
2314
+
2315
+ else:
2316
+ # No stripped state provided
2317
+ sliding_sync_insert_map["has_known_state"] = False
2318
+ sliding_sync_insert_map["room_type"] = None
2319
+ sliding_sync_insert_map["room_name"] = None
2320
+ sliding_sync_insert_map["is_encrypted"] = False
2321
+ else:
2322
+ # No stripped state provided
2323
+ sliding_sync_insert_map["has_known_state"] = False
2324
+ sliding_sync_insert_map["room_type"] = None
2325
+ sliding_sync_insert_map["room_name"] = None
2326
+ sliding_sync_insert_map["is_encrypted"] = False
2327
+
2328
+ return sliding_sync_insert_map
2329
+
2330
+ def _update_sliding_sync_tables_with_new_persisted_events_txn(
2331
+ self,
2332
+ txn: LoggingTransaction,
2333
+ room_id: str,
2334
+ events_and_contexts: list[EventPersistencePair],
2335
+ ) -> None:
2336
+ """
2337
+ Update the latest `event_stream_ordering`/`bump_stamp` columns in the
2338
+ `sliding_sync_joined_rooms` table for the room with new events.
2339
+
2340
+ This function assumes that `_store_event_txn()` (to persist the event) and
2341
+ `_update_current_state_txn(...)` (so that `sliding_sync_joined_rooms` table has
2342
+ been updated with rooms that were joined) have already been run.
2343
+
2344
+ Args:
2345
+ txn
2346
+ room_id: The room that all of the events belong to
2347
+ events_and_contexts: The events being persisted. We assume the list is
2348
+ sorted ascending by `stream_ordering`. We don't care about the sort when the
2349
+ events are backfilled (with negative `stream_ordering`).
2350
+ """
2351
+
2352
+ # Nothing to do if there are no events
2353
+ if len(events_and_contexts) == 0:
2354
+ return
2355
+
2356
+ # Since the list is sorted ascending by `stream_ordering`, the last event should
2357
+ # have the highest `stream_ordering`.
2358
+ max_stream_ordering = events_and_contexts[-1][
2359
+ 0
2360
+ ].internal_metadata.stream_ordering
2361
+ # `stream_ordering` should be assigned for persisted events
2362
+ assert max_stream_ordering is not None
2363
+ # Check if the event is a backfilled event (with a negative `stream_ordering`).
2364
+ # If one event is backfilled, we assume this whole batch was backfilled.
2365
+ if max_stream_ordering < 0:
2366
+ # We only update the sliding sync tables for non-backfilled events.
2367
+ return
2368
+
2369
+ max_bump_stamp = None
2370
+ for event, _ in reversed(events_and_contexts):
2371
+ # Sanity check that all events belong to the same room
2372
+ assert event.room_id == room_id
2373
+
2374
+ if event.type in SLIDING_SYNC_DEFAULT_BUMP_EVENT_TYPES:
2375
+ # `stream_ordering` should be assigned for persisted events
2376
+ assert event.internal_metadata.stream_ordering is not None
2377
+
2378
+ max_bump_stamp = event.internal_metadata.stream_ordering
2379
+
2380
+ # Since we're iterating in reverse, we can break as soon as we find a
2381
+ # matching bump event which should have the highest `stream_ordering`.
2382
+ break
2383
+
2384
+ # Handle updating the `sliding_sync_joined_rooms` table.
2385
+ #
2386
+ txn.execute(
2387
+ """
2388
+ UPDATE sliding_sync_joined_rooms
2389
+ SET
2390
+ event_stream_ordering = CASE
2391
+ WHEN event_stream_ordering IS NULL OR event_stream_ordering < ?
2392
+ THEN ?
2393
+ ELSE event_stream_ordering
2394
+ END,
2395
+ bump_stamp = CASE
2396
+ WHEN bump_stamp IS NULL OR bump_stamp < ?
2397
+ THEN ?
2398
+ ELSE bump_stamp
2399
+ END
2400
+ WHERE room_id = ?
2401
+ """,
2402
+ (
2403
+ max_stream_ordering,
2404
+ max_stream_ordering,
2405
+ max_bump_stamp,
2406
+ max_bump_stamp,
2407
+ room_id,
2408
+ ),
2409
+ )
2410
+ # This may or may not update any rows depending if we are `no_longer_in_room`
2411
+
2412
+ def _upsert_room_version_txn(self, txn: LoggingTransaction, room_id: str) -> None:
2413
+ """Update the room version in the database based off current state
2414
+ events.
2415
+
2416
+ This is used when we're about to delete current state and we want to
2417
+ ensure that the `rooms.room_version` column is up to date.
2418
+ """
2419
+
2420
+ sql = """
2421
+ SELECT json FROM event_json
2422
+ INNER JOIN current_state_events USING (room_id, event_id)
2423
+ WHERE room_id = ? AND type = ? AND state_key = ?
2424
+ """
2425
+ txn.execute(sql, (room_id, EventTypes.Create, ""))
2426
+ row = txn.fetchone()
2427
+ if row:
2428
+ event_json = db_to_json(row[0])
2429
+ content = event_json.get("content", {})
2430
+ creator = content.get("creator")
2431
+ room_version_id = content.get("room_version", RoomVersions.V1.identifier)
2432
+
2433
+ self.db_pool.simple_upsert_txn(
2434
+ txn,
2435
+ table="rooms",
2436
+ keyvalues={"room_id": room_id},
2437
+ values={"room_version": room_version_id},
2438
+ insertion_values={"is_public": False, "creator": creator},
2439
+ )
2440
+
2441
+ def _update_forward_extremities_txn(
2442
+ self,
2443
+ txn: LoggingTransaction,
2444
+ room_id: str,
2445
+ new_forward_extremities: set[str],
2446
+ max_stream_order: int,
2447
+ ) -> None:
2448
+ self.db_pool.simple_delete_txn(
2449
+ txn, table="event_forward_extremities", keyvalues={"room_id": room_id}
2450
+ )
2451
+
2452
+ self.db_pool.simple_insert_many_txn(
2453
+ txn,
2454
+ table="event_forward_extremities",
2455
+ keys=("event_id", "room_id"),
2456
+ values=[(ev_id, room_id) for ev_id in new_forward_extremities],
2457
+ )
2458
+ # We now insert into stream_ordering_to_exterm a mapping from room_id,
2459
+ # new stream_ordering to new forward extremeties in the room.
2460
+ # This allows us to later efficiently look up the forward extremeties
2461
+ # for a room before a given stream_ordering
2462
+ self.db_pool.simple_insert_many_txn(
2463
+ txn,
2464
+ table="stream_ordering_to_exterm",
2465
+ keys=("room_id", "event_id", "stream_ordering"),
2466
+ values=[
2467
+ (room_id, event_id, max_stream_order)
2468
+ for event_id in new_forward_extremities
2469
+ ],
2470
+ )
2471
+
2472
+ @classmethod
2473
+ def _filter_events_and_contexts_for_duplicates(
2474
+ cls, events_and_contexts: list[EventPersistencePair]
2475
+ ) -> list[EventPersistencePair]:
2476
+ """Ensure that we don't have the same event twice.
2477
+
2478
+ Pick the earliest non-outlier if there is one, else the earliest one.
2479
+
2480
+ Args:
2481
+ events_and_contexts:
2482
+
2483
+ Returns:
2484
+ filtered list
2485
+ """
2486
+ new_events_and_contexts: OrderedDict[str, EventPersistencePair] = OrderedDict()
2487
+ for event, context in events_and_contexts:
2488
+ prev_event_context = new_events_and_contexts.get(event.event_id)
2489
+ if prev_event_context:
2490
+ if not event.internal_metadata.is_outlier():
2491
+ if prev_event_context[0].internal_metadata.is_outlier():
2492
+ # To ensure correct ordering we pop, as OrderedDict is
2493
+ # ordered by first insertion.
2494
+ new_events_and_contexts.pop(event.event_id, None)
2495
+ new_events_and_contexts[event.event_id] = (event, context)
2496
+ else:
2497
+ new_events_and_contexts[event.event_id] = (event, context)
2498
+ return list(new_events_and_contexts.values())
2499
+
2500
+ def _update_room_depths_txn(
2501
+ self,
2502
+ txn: LoggingTransaction,
2503
+ room_id: str,
2504
+ events_and_contexts: list[EventPersistencePair],
2505
+ ) -> None:
2506
+ """Update min_depth for each room
2507
+
2508
+ Args:
2509
+ txn: db connection
2510
+ room_id: The room ID
2511
+ events_and_contexts: events we are persisting
2512
+ """
2513
+ stream_ordering: int | None = None
2514
+ depth_update = 0
2515
+ for event, context in events_and_contexts:
2516
+ # Don't update the stream ordering for backfilled events because
2517
+ # backfilled events have negative stream_ordering and happened in the
2518
+ # past, so we know that we don't need to update the stream_ordering
2519
+ # tip/front for the room.
2520
+ assert event.internal_metadata.stream_ordering is not None
2521
+ if event.internal_metadata.stream_ordering >= 0:
2522
+ if stream_ordering is None:
2523
+ stream_ordering = event.internal_metadata.stream_ordering
2524
+ else:
2525
+ stream_ordering = max(
2526
+ stream_ordering, event.internal_metadata.stream_ordering
2527
+ )
2528
+
2529
+ if not event.internal_metadata.is_outlier() and not context.rejected:
2530
+ depth_update = max(event.depth, depth_update)
2531
+
2532
+ # Then update the `stream_ordering` position to mark the latest event as
2533
+ # the front of the room.
2534
+ if stream_ordering is not None:
2535
+ txn.call_after(
2536
+ self.store._events_stream_cache.entity_has_changed,
2537
+ room_id,
2538
+ stream_ordering,
2539
+ )
2540
+
2541
+ self._update_min_depth_for_room_txn(txn, room_id, depth_update)
2542
+
2543
+ def _update_outliers_txn(
2544
+ self,
2545
+ txn: LoggingTransaction,
2546
+ events_and_contexts: list[EventPersistencePair],
2547
+ ) -> list[EventPersistencePair]:
2548
+ """Update any outliers with new event info.
2549
+
2550
+ This turns outliers into ex-outliers (unless the new event was rejected), and
2551
+ also removes any other events we have already seen from the list.
2552
+
2553
+ Args:
2554
+ txn: db connection
2555
+ events_and_contexts: events we are persisting
2556
+
2557
+ Returns:
2558
+ new list, without events which are already in the events table.
2559
+
2560
+ Raises:
2561
+ PartialStateConflictError: if attempting to persist a partial state event in
2562
+ a room that has been un-partial stated.
2563
+ """
2564
+ rows = cast(
2565
+ list[tuple[str, bool]],
2566
+ self.db_pool.simple_select_many_txn(
2567
+ txn,
2568
+ "events",
2569
+ "event_id",
2570
+ [event.event_id for event, _ in events_and_contexts],
2571
+ keyvalues={},
2572
+ retcols=("event_id", "outlier"),
2573
+ ),
2574
+ )
2575
+
2576
+ have_persisted = dict(rows)
2577
+
2578
+ logger.debug(
2579
+ "_update_outliers_txn: events=%s have_persisted=%s",
2580
+ [ev.event_id for ev, _ in events_and_contexts],
2581
+ have_persisted,
2582
+ )
2583
+
2584
+ to_remove = set()
2585
+ for event, context in events_and_contexts:
2586
+ outlier_persisted = have_persisted.get(event.event_id)
2587
+ logger.debug(
2588
+ "_update_outliers_txn: event=%s outlier=%s outlier_persisted=%s",
2589
+ event.event_id,
2590
+ event.internal_metadata.is_outlier(),
2591
+ outlier_persisted,
2592
+ )
2593
+
2594
+ # Ignore events which we haven't persisted at all
2595
+ if outlier_persisted is None:
2596
+ continue
2597
+
2598
+ to_remove.add(event)
2599
+
2600
+ if context.rejected:
2601
+ # If the incoming event is rejected then we don't care if the event
2602
+ # was an outlier or not - what we have is at least as good.
2603
+ continue
2604
+
2605
+ if not event.internal_metadata.is_outlier() and outlier_persisted:
2606
+ # We received a copy of an event that we had already stored as
2607
+ # an outlier in the database. We now have some state at that event
2608
+ # so we need to update the state_groups table with that state.
2609
+ #
2610
+ # Note that we do not update the stream_ordering of the event in this
2611
+ # scenario. XXX: does this cause bugs? It will mean we won't send such
2612
+ # events down /sync. In general they will be historical events, so that
2613
+ # doesn't matter too much, but that is not always the case.
2614
+
2615
+ logger.info(
2616
+ "_update_outliers_txn: Updating state for ex-outlier event %s",
2617
+ event.event_id,
2618
+ )
2619
+
2620
+ # insert into event_to_state_groups.
2621
+ try:
2622
+ self._store_event_state_mappings_txn(txn, ((event, context),))
2623
+ except Exception:
2624
+ logger.exception("")
2625
+ raise
2626
+
2627
+ # Add an entry to the ex_outlier_stream table to replicate the
2628
+ # change in outlier status to our workers.
2629
+ stream_order = event.internal_metadata.stream_ordering
2630
+ state_group_id = context.state_group
2631
+ self.db_pool.simple_insert_txn(
2632
+ txn,
2633
+ table="ex_outlier_stream",
2634
+ values={
2635
+ "event_stream_ordering": stream_order,
2636
+ "event_id": event.event_id,
2637
+ "state_group": state_group_id,
2638
+ "instance_name": self._instance_name,
2639
+ },
2640
+ )
2641
+
2642
+ sql = "UPDATE events SET outlier = FALSE WHERE event_id = ?"
2643
+ txn.execute(sql, (event.event_id,))
2644
+
2645
+ # Update the event_backward_extremities table now that this
2646
+ # event isn't an outlier any more.
2647
+ self._update_backward_extremeties(txn, [event])
2648
+
2649
+ return [ec for ec in events_and_contexts if ec[0] not in to_remove]
2650
+
2651
+ def _store_event_txn(
2652
+ self,
2653
+ txn: LoggingTransaction,
2654
+ events_and_contexts: Collection[EventPersistencePair],
2655
+ ) -> None:
2656
+ """Insert new events into the event, event_json, redaction and
2657
+ state_events tables.
2658
+ """
2659
+
2660
+ if not events_and_contexts:
2661
+ # nothing to do here
2662
+ return
2663
+
2664
+ def event_dict(event: EventBase) -> JsonDict:
2665
+ d = event.get_dict()
2666
+ d.pop("redacted", None)
2667
+ d.pop("redacted_because", None)
2668
+ return d
2669
+
2670
+ self.db_pool.simple_insert_many_txn(
2671
+ txn,
2672
+ table="event_json",
2673
+ keys=("event_id", "room_id", "internal_metadata", "json", "format_version"),
2674
+ values=[
2675
+ (
2676
+ event.event_id,
2677
+ event.room_id,
2678
+ json_encoder.encode(event.internal_metadata.get_dict()),
2679
+ json_encoder.encode(event_dict(event)),
2680
+ event.format_version,
2681
+ )
2682
+ for event, _ in events_and_contexts
2683
+ ],
2684
+ )
2685
+
2686
+ self.db_pool.simple_insert_many_txn(
2687
+ txn,
2688
+ table="events",
2689
+ keys=(
2690
+ "instance_name",
2691
+ "stream_ordering",
2692
+ "topological_ordering",
2693
+ "depth",
2694
+ "event_id",
2695
+ "room_id",
2696
+ "type",
2697
+ "processed",
2698
+ "outlier",
2699
+ "origin_server_ts",
2700
+ "received_ts",
2701
+ "sender",
2702
+ "contains_url",
2703
+ "state_key",
2704
+ "rejection_reason",
2705
+ ),
2706
+ values=[
2707
+ (
2708
+ self._instance_name,
2709
+ event.internal_metadata.stream_ordering,
2710
+ event.depth, # topological_ordering
2711
+ event.depth, # depth
2712
+ event.event_id,
2713
+ event.room_id,
2714
+ event.type,
2715
+ True, # processed
2716
+ event.internal_metadata.is_outlier(),
2717
+ int(event.origin_server_ts),
2718
+ self._clock.time_msec(),
2719
+ event.sender,
2720
+ "url" in event.content and isinstance(event.content["url"], str),
2721
+ event.get_state_key(),
2722
+ context.rejected,
2723
+ )
2724
+ for event, context in events_and_contexts
2725
+ ],
2726
+ )
2727
+
2728
+ # If we're persisting an unredacted event we go and ensure
2729
+ # that we mark any redactions that reference this event as
2730
+ # requiring censoring.
2731
+ unredacted_events = [
2732
+ event.event_id
2733
+ for event, _ in events_and_contexts
2734
+ if not event.internal_metadata.is_redacted()
2735
+ ]
2736
+ sql = "UPDATE redactions SET have_censored = FALSE WHERE "
2737
+ clause, args = make_in_list_sql_clause(
2738
+ self.database_engine,
2739
+ "redacts",
2740
+ unredacted_events,
2741
+ )
2742
+ txn.execute(sql + clause, args)
2743
+
2744
+ self.db_pool.simple_insert_many_txn(
2745
+ txn,
2746
+ table="state_events",
2747
+ keys=("event_id", "room_id", "type", "state_key"),
2748
+ values=[
2749
+ (event.event_id, event.room_id, event.type, event.state_key)
2750
+ for event, _ in events_and_contexts
2751
+ if event.is_state()
2752
+ ],
2753
+ )
2754
+
2755
+ def _store_rejected_events_txn(
2756
+ self,
2757
+ txn: LoggingTransaction,
2758
+ events_and_contexts: list[EventPersistencePair],
2759
+ ) -> list[EventPersistencePair]:
2760
+ """Add rows to the 'rejections' table for received events which were
2761
+ rejected
2762
+
2763
+ Args:
2764
+ txn: db connection
2765
+ events_and_contexts: events we are persisting
2766
+
2767
+ Returns:
2768
+ new list, without the rejected events.
2769
+ """
2770
+ # Remove the rejected events from the list now that we've added them
2771
+ # to the events table and the events_json table.
2772
+ to_remove = set()
2773
+ for event, context in events_and_contexts:
2774
+ if context.rejected:
2775
+ # Insert the event_id into the rejections table
2776
+ # (events.rejection_reason has already been done)
2777
+ self._store_rejections_txn(txn, event.event_id, context.rejected)
2778
+ to_remove.add(event)
2779
+
2780
+ return [ec for ec in events_and_contexts if ec[0] not in to_remove]
2781
+
2782
+ def _update_metadata_tables_txn(
2783
+ self,
2784
+ txn: LoggingTransaction,
2785
+ *,
2786
+ events_and_contexts: list[EventPersistencePair],
2787
+ all_events_and_contexts: list[EventPersistencePair],
2788
+ inhibit_local_membership_updates: bool = False,
2789
+ ) -> None:
2790
+ """Update all the miscellaneous tables for new events
2791
+
2792
+ Args:
2793
+ txn: db connection
2794
+ events_and_contexts: events we are persisting
2795
+ all_events_and_contexts: all events that we were going to persist.
2796
+ This includes events we've already persisted, etc, that wouldn't
2797
+ appear in events_and_context.
2798
+ inhibit_local_membership_updates: Stop the local_current_membership
2799
+ from being updated by these events. This should be set to True
2800
+ for backfilled events because backfilled events in the past do
2801
+ not affect the current local state.
2802
+ """
2803
+
2804
+ # Insert all the push actions into the event_push_actions table.
2805
+ self._set_push_actions_for_event_and_users_txn(
2806
+ txn,
2807
+ events_and_contexts=events_and_contexts,
2808
+ all_events_and_contexts=all_events_and_contexts,
2809
+ )
2810
+
2811
+ if not events_and_contexts:
2812
+ # nothing to do here
2813
+ return
2814
+
2815
+ for event, _ in events_and_contexts:
2816
+ if event.type == EventTypes.Redaction and event.redacts is not None:
2817
+ # Remove the entries in the event_push_actions table for the
2818
+ # redacted event.
2819
+ self._remove_push_actions_for_event_id_txn(
2820
+ txn, event.room_id, event.redacts
2821
+ )
2822
+
2823
+ # Remove from relations table.
2824
+ self._handle_redact_relations(txn, event.room_id, event.redacts)
2825
+
2826
+ # Update the event_forward_extremities, event_backward_extremities and
2827
+ # event_edges tables.
2828
+ self._handle_mult_prev_events(
2829
+ txn, events=[event for event, _ in events_and_contexts]
2830
+ )
2831
+
2832
+ for event, _ in events_and_contexts:
2833
+ if event.type == EventTypes.Name:
2834
+ # Insert into the event_search table.
2835
+ self._store_room_name_txn(txn, event)
2836
+ elif event.type == EventTypes.Topic:
2837
+ # Insert into the event_search table.
2838
+ self._store_room_topic_txn(txn, event)
2839
+ elif event.type == EventTypes.Message:
2840
+ # Insert into the event_search table.
2841
+ self._store_room_message_txn(txn, event)
2842
+ elif event.type == EventTypes.Redaction and event.redacts is not None:
2843
+ # Insert into the redactions table.
2844
+ self._store_redaction(txn, event)
2845
+ elif event.type == EventTypes.Retention:
2846
+ # Update the room_retention table.
2847
+ self._store_retention_policy_for_room_txn(txn, event)
2848
+
2849
+ self._handle_event_relations(txn, event)
2850
+
2851
+ # Store the labels for this event.
2852
+ labels = event.content.get(EventContentFields.LABELS)
2853
+ if labels:
2854
+ self.insert_labels_for_event_txn(
2855
+ txn, event.event_id, labels, event.room_id, event.depth
2856
+ )
2857
+
2858
+ if self._ephemeral_messages_enabled:
2859
+ # If there's an expiry timestamp on the event, store it.
2860
+ expiry_ts = event.content.get(EventContentFields.SELF_DESTRUCT_AFTER)
2861
+ if type(expiry_ts) is int and not event.is_state(): # noqa: E721
2862
+ self._insert_event_expiry_txn(txn, event.event_id, expiry_ts)
2863
+
2864
+ # Insert into the room_memberships table.
2865
+ self._store_room_members_txn(
2866
+ txn,
2867
+ [
2868
+ event
2869
+ for event, _ in events_and_contexts
2870
+ if event.type == EventTypes.Member
2871
+ ],
2872
+ inhibit_local_membership_updates=inhibit_local_membership_updates,
2873
+ )
2874
+
2875
+ # Prefill the event cache
2876
+ self._add_to_cache(txn, events_and_contexts)
2877
+
2878
+ def _add_to_cache(
2879
+ self,
2880
+ txn: LoggingTransaction,
2881
+ events_and_contexts: list[EventPersistencePair],
2882
+ ) -> None:
2883
+ to_prefill: list[EventCacheEntry] = []
2884
+
2885
+ ev_map = {e.event_id: e for e, _ in events_and_contexts}
2886
+ if not ev_map:
2887
+ return
2888
+
2889
+ sql = (
2890
+ "SELECT "
2891
+ " e.event_id as event_id, "
2892
+ " r.redacts as redacts,"
2893
+ " rej.event_id as rejects "
2894
+ " FROM events as e"
2895
+ " LEFT JOIN rejections as rej USING (event_id)"
2896
+ " LEFT JOIN redactions as r ON e.event_id = r.redacts"
2897
+ " WHERE "
2898
+ )
2899
+
2900
+ clause, args = make_in_list_sql_clause(
2901
+ self.database_engine, "e.event_id", list(ev_map)
2902
+ )
2903
+
2904
+ txn.execute(sql + clause, args)
2905
+ for event_id, redacts, rejects in txn:
2906
+ event = ev_map[event_id]
2907
+ if not rejects and not redacts:
2908
+ to_prefill.append(EventCacheEntry(event=event, redacted_event=None))
2909
+
2910
+ async def external_prefill() -> None:
2911
+ for cache_entry in to_prefill:
2912
+ await self.store._get_event_cache.set_external(
2913
+ (cache_entry.event.event_id,), cache_entry
2914
+ )
2915
+
2916
+ def local_prefill() -> None:
2917
+ for cache_entry in to_prefill:
2918
+ self.store._get_event_cache.set_local(
2919
+ (cache_entry.event.event_id,), cache_entry
2920
+ )
2921
+
2922
+ # The order these are called here is not as important as knowing that after the
2923
+ # transaction is finished, the async_call_after will run before the call_after.
2924
+ txn.async_call_after(external_prefill)
2925
+ txn.call_after(local_prefill)
2926
+
2927
+ def _store_redaction(self, txn: LoggingTransaction, event: EventBase) -> None:
2928
+ assert event.redacts is not None
2929
+ self.db_pool.simple_upsert_txn(
2930
+ txn,
2931
+ table="redactions",
2932
+ keyvalues={"event_id": event.event_id},
2933
+ values={
2934
+ "redacts": event.redacts,
2935
+ "received_ts": self._clock.time_msec(),
2936
+ },
2937
+ )
2938
+
2939
+ def insert_labels_for_event_txn(
2940
+ self,
2941
+ txn: LoggingTransaction,
2942
+ event_id: str,
2943
+ labels: list[str],
2944
+ room_id: str,
2945
+ topological_ordering: int,
2946
+ ) -> None:
2947
+ """Store the mapping between an event's ID and its labels, with one row per
2948
+ (event_id, label) tuple.
2949
+
2950
+ Args:
2951
+ txn: The transaction to execute.
2952
+ event_id: The event's ID.
2953
+ labels: A list of text labels.
2954
+ room_id: The ID of the room the event was sent to.
2955
+ topological_ordering: The position of the event in the room's topology.
2956
+ """
2957
+ self.db_pool.simple_insert_many_txn(
2958
+ txn=txn,
2959
+ table="event_labels",
2960
+ keys=("event_id", "label", "room_id", "topological_ordering"),
2961
+ values=[
2962
+ (event_id, label, room_id, topological_ordering) for label in labels
2963
+ ],
2964
+ )
2965
+
2966
+ def _insert_event_expiry_txn(
2967
+ self, txn: LoggingTransaction, event_id: str, expiry_ts: int
2968
+ ) -> None:
2969
+ """Save the expiry timestamp associated with a given event ID.
2970
+
2971
+ Args:
2972
+ txn: The database transaction to use.
2973
+ event_id: The event ID the expiry timestamp is associated with.
2974
+ expiry_ts: The timestamp at which to expire (delete) the event.
2975
+ """
2976
+ self.db_pool.simple_insert_txn(
2977
+ txn=txn,
2978
+ table="event_expiry",
2979
+ values={"event_id": event_id, "expiry_ts": expiry_ts},
2980
+ )
2981
+
2982
+ def _store_room_members_txn(
2983
+ self,
2984
+ txn: LoggingTransaction,
2985
+ events: list[EventBase],
2986
+ *,
2987
+ inhibit_local_membership_updates: bool = False,
2988
+ ) -> None:
2989
+ """
2990
+ Store a room member in the database.
2991
+
2992
+ Args:
2993
+ txn: The transaction to use.
2994
+ events: List of events to store.
2995
+ inhibit_local_membership_updates: Stop the local_current_membership
2996
+ from being updated by these events. This should be set to True
2997
+ for backfilled events because backfilled events in the past do
2998
+ not affect the current local state.
2999
+ """
3000
+
3001
+ self.db_pool.simple_insert_many_txn(
3002
+ txn,
3003
+ table="room_memberships",
3004
+ keys=(
3005
+ "event_id",
3006
+ "event_stream_ordering",
3007
+ "user_id",
3008
+ "sender",
3009
+ "room_id",
3010
+ "membership",
3011
+ "display_name",
3012
+ "avatar_url",
3013
+ ),
3014
+ values=[
3015
+ (
3016
+ event.event_id,
3017
+ event.internal_metadata.stream_ordering,
3018
+ event.state_key,
3019
+ event.user_id,
3020
+ event.room_id,
3021
+ event.membership,
3022
+ non_null_str_or_none(event.content.get("displayname")),
3023
+ non_null_str_or_none(event.content.get("avatar_url")),
3024
+ )
3025
+ for event in events
3026
+ ],
3027
+ )
3028
+
3029
+ for event in events:
3030
+ # Sanity check that we're working with persisted events
3031
+ assert event.internal_metadata.stream_ordering is not None
3032
+ assert event.internal_metadata.instance_name is not None
3033
+
3034
+ # We update the local_current_membership table only if the event is
3035
+ # "current", i.e., its something that has just happened.
3036
+ #
3037
+ # This will usually get updated by the `current_state_events` handling,
3038
+ # unless its an outlier, and an outlier is only "current" if it's an "out of
3039
+ # band membership", like a remote invite or a rejection of a remote invite.
3040
+ if (
3041
+ self.is_mine_id(event.state_key)
3042
+ and not inhibit_local_membership_updates
3043
+ and event.internal_metadata.is_outlier()
3044
+ and event.internal_metadata.is_out_of_band_membership()
3045
+ ):
3046
+ # The only sort of out-of-band-membership events we expect to see here
3047
+ # are remote invites/knocks and LEAVE events corresponding to
3048
+ # rejected/retracted invites and rescinded knocks.
3049
+ assert event.type == EventTypes.Member
3050
+ assert event.membership in (
3051
+ Membership.INVITE,
3052
+ Membership.KNOCK,
3053
+ Membership.LEAVE,
3054
+ )
3055
+
3056
+ self.db_pool.simple_upsert_txn(
3057
+ txn,
3058
+ table="local_current_membership",
3059
+ keyvalues={"room_id": event.room_id, "user_id": event.state_key},
3060
+ values={
3061
+ "event_id": event.event_id,
3062
+ "event_stream_ordering": event.internal_metadata.stream_ordering,
3063
+ "membership": event.membership,
3064
+ },
3065
+ )
3066
+
3067
+ # Handle updating the `sliding_sync_membership_snapshots` table
3068
+ # (out-of-band membership events only)
3069
+ #
3070
+ raw_stripped_state_events = None
3071
+ if event.membership == Membership.INVITE:
3072
+ invite_room_state = event.unsigned.get("invite_room_state")
3073
+ raw_stripped_state_events = invite_room_state
3074
+ elif event.membership == Membership.KNOCK:
3075
+ knock_room_state = event.unsigned.get("knock_room_state")
3076
+ raw_stripped_state_events = knock_room_state
3077
+
3078
+ insert_values = {
3079
+ "sender": event.sender,
3080
+ "membership_event_id": event.event_id,
3081
+ "membership": event.membership,
3082
+ # Since this is a new membership, it isn't forgotten anymore (which
3083
+ # matches how Synapse currently thinks about the forgotten status)
3084
+ "forgotten": 0,
3085
+ "event_stream_ordering": event.internal_metadata.stream_ordering,
3086
+ "event_instance_name": event.internal_metadata.instance_name,
3087
+ }
3088
+ if event.membership == Membership.LEAVE:
3089
+ # Inherit the meta data from the remote invite/knock. When using
3090
+ # sliding sync filters, this will prevent the room from
3091
+ # disappearing/appearing just because you left the room.
3092
+ pass
3093
+ elif event.membership in (Membership.INVITE, Membership.KNOCK):
3094
+ extra_insert_values = (
3095
+ self._get_sliding_sync_insert_values_from_stripped_state(
3096
+ raw_stripped_state_events
3097
+ )
3098
+ )
3099
+ insert_values.update(extra_insert_values)
3100
+ else:
3101
+ # We don't know how to handle this type of membership yet
3102
+ #
3103
+ # FIXME: We should use `assert_never` here but for some reason
3104
+ # the exhaustive matching doesn't recognize the `Never` here.
3105
+ # assert_never(event.membership)
3106
+ raise AssertionError(
3107
+ f"Unexpected out-of-band membership {event.membership} ({event.event_id}) that we don't know how to handle yet"
3108
+ )
3109
+
3110
+ self.db_pool.simple_upsert_txn(
3111
+ txn,
3112
+ table="sliding_sync_membership_snapshots",
3113
+ keyvalues={
3114
+ "room_id": event.room_id,
3115
+ "user_id": event.state_key,
3116
+ },
3117
+ values=insert_values,
3118
+ )
3119
+
3120
+ def _handle_event_relations(
3121
+ self, txn: LoggingTransaction, event: EventBase
3122
+ ) -> None:
3123
+ """Handles inserting relation data during persistence of events
3124
+
3125
+ Args:
3126
+ txn: The current database transaction.
3127
+ event: The event which might have relations.
3128
+ """
3129
+ relation = relation_from_event(event)
3130
+ if not relation:
3131
+ # No relation, nothing to do.
3132
+ return
3133
+
3134
+ self.db_pool.simple_insert_txn(
3135
+ txn,
3136
+ table="event_relations",
3137
+ values={
3138
+ "event_id": event.event_id,
3139
+ "relates_to_id": relation.parent_id,
3140
+ "relation_type": relation.rel_type,
3141
+ "aggregation_key": relation.aggregation_key,
3142
+ },
3143
+ )
3144
+
3145
+ if relation.rel_type == RelationTypes.THREAD:
3146
+ # Upsert into the threads table, but only overwrite the value if the
3147
+ # new event is of a later topological order OR if the topological
3148
+ # ordering is equal, but the stream ordering is later.
3149
+ # (Note by definition that the stream ordering will always be later
3150
+ # unless this is a backfilled event [= negative stream ordering]
3151
+ # because we are only persisting this event now and stream_orderings
3152
+ # are strictly monotonically increasing)
3153
+ sql = """
3154
+ INSERT INTO threads (room_id, thread_id, latest_event_id, topological_ordering, stream_ordering)
3155
+ VALUES (?, ?, ?, ?, ?)
3156
+ ON CONFLICT (room_id, thread_id)
3157
+ DO UPDATE SET
3158
+ latest_event_id = excluded.latest_event_id,
3159
+ topological_ordering = excluded.topological_ordering,
3160
+ stream_ordering = excluded.stream_ordering
3161
+ WHERE
3162
+ threads.topological_ordering <= excluded.topological_ordering AND
3163
+ threads.stream_ordering < excluded.stream_ordering
3164
+ """
3165
+
3166
+ txn.execute(
3167
+ sql,
3168
+ (
3169
+ event.room_id,
3170
+ relation.parent_id,
3171
+ event.event_id,
3172
+ event.depth,
3173
+ event.internal_metadata.stream_ordering,
3174
+ ),
3175
+ )
3176
+
3177
+ def _handle_redact_relations(
3178
+ self, txn: LoggingTransaction, room_id: str, redacted_event_id: str
3179
+ ) -> None:
3180
+ """Handles receiving a redaction and checking whether the redacted event
3181
+ has any relations which must be removed from the database.
3182
+
3183
+ Args:
3184
+ txn
3185
+ room_id: The room ID of the event that was redacted.
3186
+ redacted_event_id: The event that was redacted.
3187
+ """
3188
+
3189
+ # Fetch the relation of the event being redacted.
3190
+ row = self.db_pool.simple_select_one_txn(
3191
+ txn,
3192
+ table="event_relations",
3193
+ keyvalues={"event_id": redacted_event_id},
3194
+ retcols=("relates_to_id", "relation_type"),
3195
+ allow_none=True,
3196
+ )
3197
+ # Nothing to do if no relation is found.
3198
+ if row is None:
3199
+ return
3200
+
3201
+ redacted_relates_to, rel_type = row
3202
+ self.db_pool.simple_delete_txn(
3203
+ txn, table="event_relations", keyvalues={"event_id": redacted_event_id}
3204
+ )
3205
+
3206
+ # Any relation information for the related event must be cleared.
3207
+ self.store._invalidate_cache_and_stream(
3208
+ txn,
3209
+ self.store.get_relations_for_event,
3210
+ (
3211
+ room_id,
3212
+ redacted_relates_to,
3213
+ ),
3214
+ )
3215
+ if rel_type == RelationTypes.REFERENCE:
3216
+ self.store._invalidate_cache_and_stream(
3217
+ txn, self.store.get_references_for_event, (redacted_relates_to,)
3218
+ )
3219
+ if rel_type == RelationTypes.REPLACE:
3220
+ self.store._invalidate_cache_and_stream(
3221
+ txn, self.store.get_applicable_edit, (redacted_relates_to,)
3222
+ )
3223
+ if rel_type == RelationTypes.THREAD:
3224
+ self.store._invalidate_cache_and_stream(
3225
+ txn, self.store.get_thread_summary, (redacted_relates_to,)
3226
+ )
3227
+ self.store._invalidate_cache_and_stream(
3228
+ txn, self.store.get_thread_participated, (redacted_relates_to,)
3229
+ )
3230
+ self.store._invalidate_cache_and_stream(
3231
+ txn, self.store.get_threads, (room_id,)
3232
+ )
3233
+
3234
+ # Find the new latest event in the thread.
3235
+ sql = """
3236
+ SELECT event_id, topological_ordering, stream_ordering
3237
+ FROM event_relations
3238
+ INNER JOIN events USING (event_id)
3239
+ WHERE relates_to_id = ? AND relation_type = ?
3240
+ ORDER BY topological_ordering DESC, stream_ordering DESC
3241
+ LIMIT 1
3242
+ """
3243
+ txn.execute(sql, (redacted_relates_to, RelationTypes.THREAD))
3244
+
3245
+ # If a latest event is found, update the threads table, this might
3246
+ # be the same current latest event (if an earlier event in the thread
3247
+ # was redacted).
3248
+ latest_event_row = txn.fetchone()
3249
+ if latest_event_row:
3250
+ self.db_pool.simple_upsert_txn(
3251
+ txn,
3252
+ table="threads",
3253
+ keyvalues={"room_id": room_id, "thread_id": redacted_relates_to},
3254
+ values={
3255
+ "latest_event_id": latest_event_row[0],
3256
+ "topological_ordering": latest_event_row[1],
3257
+ "stream_ordering": latest_event_row[2],
3258
+ },
3259
+ )
3260
+
3261
+ # Otherwise, delete the thread: it no longer exists.
3262
+ else:
3263
+ self.db_pool.simple_delete_one_txn(
3264
+ txn, table="threads", keyvalues={"thread_id": redacted_relates_to}
3265
+ )
3266
+
3267
+ def _store_room_topic_txn(self, txn: LoggingTransaction, event: EventBase) -> None:
3268
+ if isinstance(event.content.get("topic"), str):
3269
+ self.store_event_search_txn(
3270
+ txn,
3271
+ event,
3272
+ "content.topic",
3273
+ get_plain_text_topic_from_event_content(event.content) or "",
3274
+ )
3275
+
3276
+ def _store_room_name_txn(self, txn: LoggingTransaction, event: EventBase) -> None:
3277
+ if isinstance(event.content.get("name"), str):
3278
+ self.store_event_search_txn(
3279
+ txn, event, "content.name", event.content["name"]
3280
+ )
3281
+
3282
+ def _store_room_message_txn(
3283
+ self, txn: LoggingTransaction, event: EventBase
3284
+ ) -> None:
3285
+ if isinstance(event.content.get("body"), str):
3286
+ self.store_event_search_txn(
3287
+ txn, event, "content.body", event.content["body"]
3288
+ )
3289
+
3290
+ def _store_retention_policy_for_room_txn(
3291
+ self, txn: LoggingTransaction, event: EventBase
3292
+ ) -> None:
3293
+ if not event.is_state():
3294
+ logger.debug("Ignoring non-state m.room.retention event")
3295
+ return
3296
+
3297
+ if hasattr(event, "content") and (
3298
+ "min_lifetime" in event.content or "max_lifetime" in event.content
3299
+ ):
3300
+ if (
3301
+ "min_lifetime" in event.content
3302
+ and type(event.content["min_lifetime"]) is not int # noqa: E721
3303
+ ) or (
3304
+ "max_lifetime" in event.content
3305
+ and type(event.content["max_lifetime"]) is not int # noqa: E721
3306
+ ):
3307
+ # Ignore the event if one of the value isn't an integer.
3308
+ return
3309
+
3310
+ self.db_pool.simple_insert_txn(
3311
+ txn=txn,
3312
+ table="room_retention",
3313
+ values={
3314
+ "room_id": event.room_id,
3315
+ "event_id": event.event_id,
3316
+ "min_lifetime": event.content.get("min_lifetime"),
3317
+ "max_lifetime": event.content.get("max_lifetime"),
3318
+ },
3319
+ )
3320
+
3321
+ self.store._invalidate_cache_and_stream(
3322
+ txn, self.store.get_retention_policy_for_room, (event.room_id,)
3323
+ )
3324
+
3325
+ def store_event_search_txn(
3326
+ self, txn: LoggingTransaction, event: EventBase, key: str, value: str
3327
+ ) -> None:
3328
+ """Add event to the search table
3329
+
3330
+ Args:
3331
+ txn: The database transaction.
3332
+ event: The event being added to the search table.
3333
+ key: A key describing the search value (one of "content.name",
3334
+ "content.topic", or "content.body")
3335
+ value: The value from the event's content.
3336
+ """
3337
+ self.store.store_search_entries_txn(
3338
+ txn,
3339
+ (
3340
+ SearchEntry(
3341
+ key=key,
3342
+ value=value,
3343
+ event_id=event.event_id,
3344
+ room_id=event.room_id,
3345
+ stream_ordering=event.internal_metadata.stream_ordering,
3346
+ origin_server_ts=event.origin_server_ts,
3347
+ ),
3348
+ ),
3349
+ )
3350
+
3351
+ def _set_push_actions_for_event_and_users_txn(
3352
+ self,
3353
+ txn: LoggingTransaction,
3354
+ events_and_contexts: list[EventPersistencePair],
3355
+ all_events_and_contexts: list[EventPersistencePair],
3356
+ ) -> None:
3357
+ """Handles moving push actions from staging table to main
3358
+ event_push_actions table for all events in `events_and_contexts`.
3359
+
3360
+ Also ensures that all events in `all_events_and_contexts` are removed
3361
+ from the push action staging area.
3362
+
3363
+ Args:
3364
+ events_and_contexts: events we are persisting
3365
+ all_events_and_contexts: all events that we were going to persist.
3366
+ This includes events we've already persisted, etc, that wouldn't
3367
+ appear in events_and_context.
3368
+ """
3369
+
3370
+ # Only notifiable events will have push actions associated with them,
3371
+ # so let's filter them out. (This makes joining large rooms faster, as
3372
+ # these queries took seconds to process all the state events).
3373
+ notifiable_events = [
3374
+ event
3375
+ for event, _ in events_and_contexts
3376
+ if event.internal_metadata.is_notifiable()
3377
+ ]
3378
+
3379
+ sql = """
3380
+ INSERT INTO event_push_actions (
3381
+ room_id, event_id, user_id, actions, stream_ordering,
3382
+ topological_ordering, notif, highlight, unread, thread_id
3383
+ )
3384
+ SELECT ?, event_id, user_id, actions, ?, ?, notif, highlight, unread, thread_id
3385
+ FROM event_push_actions_staging
3386
+ WHERE event_id = ?
3387
+ """
3388
+
3389
+ if notifiable_events:
3390
+ txn.execute_batch(
3391
+ sql,
3392
+ [
3393
+ (
3394
+ event.room_id,
3395
+ event.internal_metadata.stream_ordering,
3396
+ event.depth,
3397
+ event.event_id,
3398
+ )
3399
+ for event in notifiable_events
3400
+ ],
3401
+ )
3402
+
3403
+ # Now we delete the staging area for *all* events that were being
3404
+ # persisted.
3405
+ txn.execute_batch(
3406
+ "DELETE FROM event_push_actions_staging WHERE event_id = ?",
3407
+ [
3408
+ (event.event_id,)
3409
+ for event, _ in all_events_and_contexts
3410
+ if event.internal_metadata.is_notifiable()
3411
+ ],
3412
+ )
3413
+
3414
+ def _remove_push_actions_for_event_id_txn(
3415
+ self, txn: LoggingTransaction, room_id: str, event_id: str
3416
+ ) -> None:
3417
+ txn.execute(
3418
+ "DELETE FROM event_push_actions WHERE room_id = ? AND event_id = ?",
3419
+ (room_id, event_id),
3420
+ )
3421
+
3422
+ def _store_rejections_txn(
3423
+ self, txn: LoggingTransaction, event_id: str, reason: str
3424
+ ) -> None:
3425
+ self.db_pool.simple_insert_txn(
3426
+ txn,
3427
+ table="rejections",
3428
+ values={
3429
+ "event_id": event_id,
3430
+ "reason": reason,
3431
+ "last_check": self._clock.time_msec(),
3432
+ },
3433
+ )
3434
+
3435
+ def _store_event_state_mappings_txn(
3436
+ self,
3437
+ txn: LoggingTransaction,
3438
+ events_and_contexts: Collection[EventPersistencePair],
3439
+ ) -> None:
3440
+ """
3441
+ Raises:
3442
+ PartialStateConflictError: if attempting to persist a partial state event in
3443
+ a room that has been un-partial stated.
3444
+ """
3445
+ state_groups = {}
3446
+ for event, context in events_and_contexts:
3447
+ if event.internal_metadata.is_outlier():
3448
+ # double-check that we don't have any events that claim to be outliers
3449
+ # *and* have partial state (which is meaningless: we should have no
3450
+ # state at all for an outlier)
3451
+ if context.partial_state:
3452
+ raise ValueError(
3453
+ "Outlier event %s claims to have partial state", event.event_id
3454
+ )
3455
+
3456
+ continue
3457
+
3458
+ # if the event was rejected, just give it the same state as its
3459
+ # predecessor.
3460
+ if context.rejected:
3461
+ state_groups[event.event_id] = context.state_group_before_event
3462
+ continue
3463
+
3464
+ state_groups[event.event_id] = context.state_group
3465
+
3466
+ # if we have partial state for these events, record the fact. (This happens
3467
+ # here rather than in _store_event_txn because it also needs to happen when
3468
+ # we de-outlier an event.)
3469
+ try:
3470
+ self.db_pool.simple_insert_many_txn(
3471
+ txn,
3472
+ table="partial_state_events",
3473
+ keys=("room_id", "event_id"),
3474
+ values=[
3475
+ (
3476
+ event.room_id,
3477
+ event.event_id,
3478
+ )
3479
+ for event, ctx in events_and_contexts
3480
+ if ctx.partial_state
3481
+ ],
3482
+ )
3483
+ except self.db_pool.engine.module.IntegrityError:
3484
+ logger.info(
3485
+ "Cannot persist events %s in rooms %s: room has been un-partial stated",
3486
+ [
3487
+ event.event_id
3488
+ for event, ctx in events_and_contexts
3489
+ if ctx.partial_state
3490
+ ],
3491
+ list(
3492
+ {
3493
+ event.room_id
3494
+ for event, ctx in events_and_contexts
3495
+ if ctx.partial_state
3496
+ }
3497
+ ),
3498
+ )
3499
+ raise PartialStateConflictError()
3500
+
3501
+ self.db_pool.simple_upsert_many_txn(
3502
+ txn,
3503
+ table="event_to_state_groups",
3504
+ key_names=["event_id"],
3505
+ key_values=[[event_id] for event_id, _ in state_groups.items()],
3506
+ value_names=["state_group"],
3507
+ value_values=[
3508
+ [state_group_id] for _, state_group_id in state_groups.items()
3509
+ ],
3510
+ )
3511
+
3512
+ for event_id, state_group_id in state_groups.items():
3513
+ txn.call_after(
3514
+ self.store._get_state_group_for_event.prefill,
3515
+ (event_id,),
3516
+ state_group_id,
3517
+ )
3518
+
3519
+ def _update_min_depth_for_room_txn(
3520
+ self, txn: LoggingTransaction, room_id: str, depth: int
3521
+ ) -> None:
3522
+ min_depth = self.store._get_min_depth_interaction(txn, room_id)
3523
+
3524
+ if min_depth is not None and depth >= min_depth:
3525
+ return
3526
+
3527
+ self.db_pool.simple_upsert_txn(
3528
+ txn,
3529
+ table="room_depth",
3530
+ keyvalues={"room_id": room_id},
3531
+ values={"min_depth": depth},
3532
+ )
3533
+
3534
+ def _handle_mult_prev_events(
3535
+ self, txn: LoggingTransaction, events: list[EventBase]
3536
+ ) -> None:
3537
+ """
3538
+ For the given event, update the event edges table and forward and
3539
+ backward extremities tables.
3540
+ """
3541
+ self.db_pool.simple_insert_many_txn(
3542
+ txn,
3543
+ table="event_edges",
3544
+ keys=("event_id", "prev_event_id"),
3545
+ values=[
3546
+ (ev.event_id, e_id) for ev in events for e_id in ev.prev_event_ids()
3547
+ ],
3548
+ )
3549
+
3550
+ self._update_backward_extremeties(txn, events)
3551
+
3552
+ def _update_backward_extremeties(
3553
+ self, txn: LoggingTransaction, events: list[EventBase]
3554
+ ) -> None:
3555
+ """Updates the event_backward_extremities tables based on the new/updated
3556
+ events being persisted.
3557
+
3558
+ This is called for new events *and* for events that were outliers, but
3559
+ are now being persisted as non-outliers.
3560
+
3561
+ Forward extremities are handled when we first start persisting the events.
3562
+ """
3563
+
3564
+ room_id = events[0].room_id
3565
+
3566
+ potential_backwards_extremities = {
3567
+ e_id
3568
+ for ev in events
3569
+ for e_id in ev.prev_event_ids()
3570
+ if not ev.internal_metadata.is_outlier()
3571
+ }
3572
+
3573
+ if not potential_backwards_extremities:
3574
+ return
3575
+
3576
+ existing_events_outliers = self.db_pool.simple_select_many_txn(
3577
+ txn,
3578
+ table="events",
3579
+ column="event_id",
3580
+ iterable=potential_backwards_extremities,
3581
+ keyvalues={"outlier": False},
3582
+ retcols=("event_id",),
3583
+ )
3584
+
3585
+ potential_backwards_extremities.difference_update(
3586
+ e for (e,) in existing_events_outliers
3587
+ )
3588
+
3589
+ if potential_backwards_extremities:
3590
+ self.db_pool.simple_upsert_many_txn(
3591
+ txn,
3592
+ table="event_backward_extremities",
3593
+ key_names=("room_id", "event_id"),
3594
+ key_values=[(room_id, ev) for ev in potential_backwards_extremities],
3595
+ value_names=(),
3596
+ value_values=(),
3597
+ )
3598
+
3599
+ # Record the stream orderings where we have new gaps.
3600
+ gap_events = [
3601
+ (room_id, self._instance_name, ev.internal_metadata.stream_ordering)
3602
+ for ev in events
3603
+ if any(
3604
+ e_id in potential_backwards_extremities
3605
+ for e_id in ev.prev_event_ids()
3606
+ )
3607
+ ]
3608
+
3609
+ self.db_pool.simple_insert_many_txn(
3610
+ txn,
3611
+ table="timeline_gaps",
3612
+ keys=("room_id", "instance_name", "stream_ordering"),
3613
+ values=gap_events,
3614
+ )
3615
+
3616
+ # Delete all these events that we've already fetched and now know that their
3617
+ # prev events are the new backwards extremeties.
3618
+ query = (
3619
+ "DELETE FROM event_backward_extremities WHERE event_id = ? AND room_id = ?"
3620
+ )
3621
+ backward_extremity_tuples_to_remove = [
3622
+ (ev.event_id, ev.room_id)
3623
+ for ev in events
3624
+ if not ev.internal_metadata.is_outlier()
3625
+ # If we encountered an event with no prev_events, then we might
3626
+ # as well remove it now because it won't ever have anything else
3627
+ # to backfill from.
3628
+ or len(ev.prev_event_ids()) == 0
3629
+ ]
3630
+ txn.execute_batch(
3631
+ query,
3632
+ backward_extremity_tuples_to_remove,
3633
+ )
3634
+
3635
+ # Clear out the failed backfill attempts after we successfully pulled
3636
+ # the event. Since we no longer need these events as backward
3637
+ # extremities, it also means that they won't be backfilled from again so
3638
+ # we no longer need to store the backfill attempts around it.
3639
+ query = """
3640
+ DELETE FROM event_failed_pull_attempts
3641
+ WHERE event_id = ? and room_id = ?
3642
+ """
3643
+ txn.execute_batch(
3644
+ query,
3645
+ backward_extremity_tuples_to_remove,
3646
+ )
3647
+
3648
+
3649
+ @attr.s(slots=True, auto_attribs=True)
3650
+ class _LinkMap:
3651
+ """A helper type for tracking links between chains."""
3652
+
3653
+ # Stores the set of links as nested maps: source chain ID -> target chain ID
3654
+ # -> source sequence number -> target sequence number.
3655
+ maps: dict[int, dict[int, dict[int, int]]] = attr.Factory(dict)
3656
+
3657
+ # Stores the links that have been added (with new set to true), as tuples of
3658
+ # `(source chain ID, source sequence no, target chain ID, target sequence no.)`
3659
+ additions: set[tuple[int, int, int, int]] = attr.Factory(set)
3660
+
3661
+ def add_link(
3662
+ self,
3663
+ src_tuple: tuple[int, int],
3664
+ target_tuple: tuple[int, int],
3665
+ new: bool = True,
3666
+ ) -> bool:
3667
+ """Add a new link between two chains, ensuring no redundant links are added.
3668
+
3669
+ New links should be added in topological order.
3670
+
3671
+ Args:
3672
+ src_tuple: The chain ID/sequence number of the source of the link.
3673
+ target_tuple: The chain ID/sequence number of the target of the link.
3674
+ new: Whether this is a "new" link, i.e. should it be returned
3675
+ by `get_additions`.
3676
+
3677
+ Returns:
3678
+ True if a link was added, false if the given link was dropped as redundant
3679
+ """
3680
+ src_chain, src_seq = src_tuple
3681
+ target_chain, target_seq = target_tuple
3682
+
3683
+ current_links = self.maps.setdefault(src_chain, {}).setdefault(target_chain, {})
3684
+
3685
+ assert src_chain != target_chain
3686
+
3687
+ if new:
3688
+ # Check if the new link is redundant
3689
+ for current_seq_src, current_seq_target in current_links.items():
3690
+ # If a link "crosses" another link then its redundant. For example
3691
+ # in the following link 1 (L1) is redundant, as any event reachable
3692
+ # via L1 is *also* reachable via L2.
3693
+ #
3694
+ # Chain A Chain B
3695
+ # | |
3696
+ # L1 |------ |
3697
+ # | | |
3698
+ # L2 |---- | -->|
3699
+ # | | |
3700
+ # | |--->|
3701
+ # | |
3702
+ # | |
3703
+ #
3704
+ # So we only need to keep links which *do not* cross, i.e. links
3705
+ # that both start and end above or below an existing link.
3706
+ #
3707
+ # Note, since we add links in topological ordering we should never
3708
+ # see `src_seq` less than `current_seq_src`.
3709
+
3710
+ if current_seq_src <= src_seq and target_seq <= current_seq_target:
3711
+ # This new link is redundant, nothing to do.
3712
+ return False
3713
+
3714
+ self.additions.add((src_chain, src_seq, target_chain, target_seq))
3715
+
3716
+ current_links[src_seq] = target_seq
3717
+ return True
3718
+
3719
+ def get_additions(self) -> Generator[tuple[int, int, int, int], None, None]:
3720
+ """Gets any newly added links.
3721
+
3722
+ Yields:
3723
+ The source chain ID/sequence number and target chain ID/sequence number
3724
+ """
3725
+
3726
+ for src_chain, src_seq, target_chain, _ in self.additions:
3727
+ target_seq = self.maps.get(src_chain, {}).get(target_chain, {}).get(src_seq)
3728
+ if target_seq is not None:
3729
+ yield (src_chain, src_seq, target_chain, target_seq)
3730
+
3731
+ def exists_path_from(
3732
+ self,
3733
+ src_tuple: tuple[int, int],
3734
+ target_tuple: tuple[int, int],
3735
+ ) -> bool:
3736
+ """Checks if there is a path between the source chain ID/sequence and
3737
+ target chain ID/sequence.
3738
+ """
3739
+ src_chain, src_seq = src_tuple
3740
+ target_chain, target_seq = target_tuple
3741
+
3742
+ if src_chain == target_chain:
3743
+ return target_seq <= src_seq
3744
+
3745
+ # We have to graph traverse the links to check for indirect paths.
3746
+ visited_chains: dict[int, int] = collections.Counter()
3747
+ search = [(src_chain, src_seq)]
3748
+ while search:
3749
+ chain, seq = search.pop()
3750
+ visited_chains[chain] = max(seq, visited_chains[chain])
3751
+ for tc, links in self.maps.get(chain, {}).items():
3752
+ for ss, ts in links.items():
3753
+ # Don't revisit chains we've already seen, unless the target
3754
+ # sequence number is higher than last time.
3755
+ if ts <= visited_chains.get(tc, 0):
3756
+ continue
3757
+
3758
+ if ss <= seq:
3759
+ if tc == target_chain:
3760
+ if target_seq <= ts:
3761
+ return True
3762
+ else:
3763
+ search.append((tc, ts))
3764
+
3765
+ return False