matrix-synapse 1.142.0rc3__cp314-abi3-musllinux_1_2_aarch64.whl

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

Potentially problematic release.


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

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