sync.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015 - 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from ._base import BaseHandler
  16. from synapse.streams.config import PaginationConfig
  17. from synapse.api.constants import Membership, EventTypes
  18. from synapse.util.async import concurrently_execute
  19. from synapse.util.logcontext import LoggingContext
  20. from synapse.util.metrics import Measure
  21. from synapse.util.caches.response_cache import ResponseCache
  22. from synapse.push.clientformat import format_push_rules_for_user
  23. from twisted.internet import defer
  24. import collections
  25. import logging
  26. import itertools
  27. logger = logging.getLogger(__name__)
  28. SyncConfig = collections.namedtuple("SyncConfig", [
  29. "user",
  30. "filter_collection",
  31. "is_guest",
  32. "request_key",
  33. ])
  34. class TimelineBatch(collections.namedtuple("TimelineBatch", [
  35. "prev_batch",
  36. "events",
  37. "limited",
  38. ])):
  39. __slots__ = []
  40. def __nonzero__(self):
  41. """Make the result appear empty if there are no updates. This is used
  42. to tell if room needs to be part of the sync result.
  43. """
  44. return bool(self.events)
  45. class JoinedSyncResult(collections.namedtuple("JoinedSyncResult", [
  46. "room_id", # str
  47. "timeline", # TimelineBatch
  48. "state", # dict[(str, str), FrozenEvent]
  49. "ephemeral",
  50. "account_data",
  51. "unread_notifications",
  52. ])):
  53. __slots__ = []
  54. def __nonzero__(self):
  55. """Make the result appear empty if there are no updates. This is used
  56. to tell if room needs to be part of the sync result.
  57. """
  58. return bool(
  59. self.timeline
  60. or self.state
  61. or self.ephemeral
  62. or self.account_data
  63. # nb the notification count does not, er, count: if there's nothing
  64. # else in the result, we don't need to send it.
  65. )
  66. class ArchivedSyncResult(collections.namedtuple("ArchivedSyncResult", [
  67. "room_id", # str
  68. "timeline", # TimelineBatch
  69. "state", # dict[(str, str), FrozenEvent]
  70. "account_data",
  71. ])):
  72. __slots__ = []
  73. def __nonzero__(self):
  74. """Make the result appear empty if there are no updates. This is used
  75. to tell if room needs to be part of the sync result.
  76. """
  77. return bool(
  78. self.timeline
  79. or self.state
  80. or self.account_data
  81. )
  82. class InvitedSyncResult(collections.namedtuple("InvitedSyncResult", [
  83. "room_id", # str
  84. "invite", # FrozenEvent: the invite event
  85. ])):
  86. __slots__ = []
  87. def __nonzero__(self):
  88. """Invited rooms should always be reported to the client"""
  89. return True
  90. class SyncResult(collections.namedtuple("SyncResult", [
  91. "next_batch", # Token for the next sync
  92. "presence", # List of presence events for the user.
  93. "account_data", # List of account_data events for the user.
  94. "joined", # JoinedSyncResult for each joined room.
  95. "invited", # InvitedSyncResult for each invited room.
  96. "archived", # ArchivedSyncResult for each archived room.
  97. ])):
  98. __slots__ = []
  99. def __nonzero__(self):
  100. """Make the result appear empty if there are no updates. This is used
  101. to tell if the notifier needs to wait for more events when polling for
  102. events.
  103. """
  104. return bool(
  105. self.presence or
  106. self.joined or
  107. self.invited or
  108. self.archived or
  109. self.account_data
  110. )
  111. class SyncHandler(BaseHandler):
  112. def __init__(self, hs):
  113. super(SyncHandler, self).__init__(hs)
  114. self.event_sources = hs.get_event_sources()
  115. self.clock = hs.get_clock()
  116. self.response_cache = ResponseCache()
  117. def wait_for_sync_for_user(self, sync_config, since_token=None, timeout=0,
  118. full_state=False):
  119. """Get the sync for a client if we have new data for it now. Otherwise
  120. wait for new data to arrive on the server. If the timeout expires, then
  121. return an empty sync result.
  122. Returns:
  123. A Deferred SyncResult.
  124. """
  125. result = self.response_cache.get(sync_config.request_key)
  126. if not result:
  127. result = self.response_cache.set(
  128. sync_config.request_key,
  129. self._wait_for_sync_for_user(
  130. sync_config, since_token, timeout, full_state
  131. )
  132. )
  133. return result
  134. @defer.inlineCallbacks
  135. def _wait_for_sync_for_user(self, sync_config, since_token, timeout,
  136. full_state):
  137. context = LoggingContext.current_context()
  138. if context:
  139. if since_token is None:
  140. context.tag = "initial_sync"
  141. elif full_state:
  142. context.tag = "full_state_sync"
  143. else:
  144. context.tag = "incremental_sync"
  145. if timeout == 0 or since_token is None or full_state:
  146. # we are going to return immediately, so don't bother calling
  147. # notifier.wait_for_events.
  148. result = yield self.current_sync_for_user(
  149. sync_config, since_token, full_state=full_state,
  150. )
  151. defer.returnValue(result)
  152. else:
  153. def current_sync_callback(before_token, after_token):
  154. return self.current_sync_for_user(sync_config, since_token)
  155. result = yield self.notifier.wait_for_events(
  156. sync_config.user.to_string(), timeout, current_sync_callback,
  157. from_token=since_token,
  158. )
  159. defer.returnValue(result)
  160. def current_sync_for_user(self, sync_config, since_token=None,
  161. full_state=False):
  162. """Get the sync for client needed to match what the server has now.
  163. Returns:
  164. A Deferred SyncResult.
  165. """
  166. if since_token is None or full_state:
  167. return self.full_state_sync(sync_config, since_token)
  168. else:
  169. return self.incremental_sync_with_gap(sync_config, since_token)
  170. @defer.inlineCallbacks
  171. def full_state_sync(self, sync_config, timeline_since_token):
  172. """Get a sync for a client which is starting without any state.
  173. If a 'message_since_token' is given, only timeline events which have
  174. happened since that token will be returned.
  175. Returns:
  176. A Deferred SyncResult.
  177. """
  178. now_token = yield self.event_sources.get_current_token()
  179. now_token, ephemeral_by_room = yield self.ephemeral_by_room(
  180. sync_config, now_token
  181. )
  182. presence_stream = self.event_sources.sources["presence"]
  183. # TODO (mjark): This looks wrong, shouldn't we be getting the presence
  184. # UP to the present rather than after the present?
  185. pagination_config = PaginationConfig(from_token=now_token)
  186. presence, _ = yield presence_stream.get_pagination_rows(
  187. user=sync_config.user,
  188. pagination_config=pagination_config.get_source_config("presence"),
  189. key=None
  190. )
  191. membership_list = (
  192. Membership.INVITE, Membership.JOIN, Membership.LEAVE, Membership.BAN
  193. )
  194. room_list = yield self.store.get_rooms_for_user_where_membership_is(
  195. user_id=sync_config.user.to_string(),
  196. membership_list=membership_list
  197. )
  198. account_data, account_data_by_room = (
  199. yield self.store.get_account_data_for_user(
  200. sync_config.user.to_string()
  201. )
  202. )
  203. account_data['m.push_rules'] = yield self.push_rules_for_user(
  204. sync_config.user
  205. )
  206. tags_by_room = yield self.store.get_tags_for_user(
  207. sync_config.user.to_string()
  208. )
  209. joined = []
  210. invited = []
  211. archived = []
  212. user_id = sync_config.user.to_string()
  213. @defer.inlineCallbacks
  214. def _generate_room_entry(event):
  215. if event.membership == Membership.JOIN:
  216. room_result = yield self.full_state_sync_for_joined_room(
  217. room_id=event.room_id,
  218. sync_config=sync_config,
  219. now_token=now_token,
  220. timeline_since_token=timeline_since_token,
  221. ephemeral_by_room=ephemeral_by_room,
  222. tags_by_room=tags_by_room,
  223. account_data_by_room=account_data_by_room,
  224. )
  225. joined.append(room_result)
  226. elif event.membership == Membership.INVITE:
  227. invite = yield self.store.get_event(event.event_id)
  228. invited.append(InvitedSyncResult(
  229. room_id=event.room_id,
  230. invite=invite,
  231. ))
  232. elif event.membership in (Membership.LEAVE, Membership.BAN):
  233. # Always send down rooms we were banned or kicked from.
  234. if not sync_config.filter_collection.include_leave:
  235. if event.membership == Membership.LEAVE:
  236. if user_id == event.sender:
  237. return
  238. leave_token = now_token.copy_and_replace(
  239. "room_key", "s%d" % (event.stream_ordering,)
  240. )
  241. room_result = yield self.full_state_sync_for_archived_room(
  242. sync_config=sync_config,
  243. room_id=event.room_id,
  244. leave_event_id=event.event_id,
  245. leave_token=leave_token,
  246. timeline_since_token=timeline_since_token,
  247. tags_by_room=tags_by_room,
  248. account_data_by_room=account_data_by_room,
  249. )
  250. archived.append(room_result)
  251. yield concurrently_execute(_generate_room_entry, room_list, 10)
  252. account_data_for_user = sync_config.filter_collection.filter_account_data(
  253. self.account_data_for_user(account_data)
  254. )
  255. presence = sync_config.filter_collection.filter_presence(
  256. presence
  257. )
  258. defer.returnValue(SyncResult(
  259. presence=presence,
  260. account_data=account_data_for_user,
  261. joined=joined,
  262. invited=invited,
  263. archived=archived,
  264. next_batch=now_token,
  265. ))
  266. @defer.inlineCallbacks
  267. def full_state_sync_for_joined_room(self, room_id, sync_config,
  268. now_token, timeline_since_token,
  269. ephemeral_by_room, tags_by_room,
  270. account_data_by_room):
  271. """Sync a room for a client which is starting without any state
  272. Returns:
  273. A Deferred JoinedSyncResult.
  274. """
  275. batch = yield self.load_filtered_recents(
  276. room_id, sync_config, now_token, since_token=timeline_since_token
  277. )
  278. room_sync = yield self.incremental_sync_with_gap_for_room(
  279. room_id, sync_config,
  280. now_token=now_token,
  281. since_token=timeline_since_token,
  282. ephemeral_by_room=ephemeral_by_room,
  283. tags_by_room=tags_by_room,
  284. account_data_by_room=account_data_by_room,
  285. batch=batch,
  286. full_state=True,
  287. )
  288. defer.returnValue(room_sync)
  289. @defer.inlineCallbacks
  290. def push_rules_for_user(self, user):
  291. user_id = user.to_string()
  292. rawrules = yield self.store.get_push_rules_for_user(user_id)
  293. enabled_map = yield self.store.get_push_rules_enabled_for_user(user_id)
  294. rules = format_push_rules_for_user(user, rawrules, enabled_map)
  295. defer.returnValue(rules)
  296. def account_data_for_user(self, account_data):
  297. account_data_events = []
  298. for account_data_type, content in account_data.items():
  299. account_data_events.append({
  300. "type": account_data_type,
  301. "content": content,
  302. })
  303. return account_data_events
  304. def account_data_for_room(self, room_id, tags_by_room, account_data_by_room):
  305. account_data_events = []
  306. tags = tags_by_room.get(room_id)
  307. if tags is not None:
  308. account_data_events.append({
  309. "type": "m.tag",
  310. "content": {"tags": tags},
  311. })
  312. account_data = account_data_by_room.get(room_id, {})
  313. for account_data_type, content in account_data.items():
  314. account_data_events.append({
  315. "type": account_data_type,
  316. "content": content,
  317. })
  318. return account_data_events
  319. @defer.inlineCallbacks
  320. def ephemeral_by_room(self, sync_config, now_token, since_token=None):
  321. """Get the ephemeral events for each room the user is in
  322. Args:
  323. sync_config (SyncConfig): The flags, filters and user for the sync.
  324. now_token (StreamToken): Where the server is currently up to.
  325. since_token (StreamToken): Where the server was when the client
  326. last synced.
  327. Returns:
  328. A tuple of the now StreamToken, updated to reflect the which typing
  329. events are included, and a dict mapping from room_id to a list of
  330. typing events for that room.
  331. """
  332. with Measure(self.clock, "ephemeral_by_room"):
  333. typing_key = since_token.typing_key if since_token else "0"
  334. rooms = yield self.store.get_rooms_for_user(sync_config.user.to_string())
  335. room_ids = [room.room_id for room in rooms]
  336. typing_source = self.event_sources.sources["typing"]
  337. typing, typing_key = yield typing_source.get_new_events(
  338. user=sync_config.user,
  339. from_key=typing_key,
  340. limit=sync_config.filter_collection.ephemeral_limit(),
  341. room_ids=room_ids,
  342. is_guest=sync_config.is_guest,
  343. )
  344. now_token = now_token.copy_and_replace("typing_key", typing_key)
  345. ephemeral_by_room = {}
  346. for event in typing:
  347. # we want to exclude the room_id from the event, but modifying the
  348. # result returned by the event source is poor form (it might cache
  349. # the object)
  350. room_id = event["room_id"]
  351. event_copy = {k: v for (k, v) in event.iteritems()
  352. if k != "room_id"}
  353. ephemeral_by_room.setdefault(room_id, []).append(event_copy)
  354. receipt_key = since_token.receipt_key if since_token else "0"
  355. receipt_source = self.event_sources.sources["receipt"]
  356. receipts, receipt_key = yield receipt_source.get_new_events(
  357. user=sync_config.user,
  358. from_key=receipt_key,
  359. limit=sync_config.filter_collection.ephemeral_limit(),
  360. room_ids=room_ids,
  361. is_guest=sync_config.is_guest,
  362. )
  363. now_token = now_token.copy_and_replace("receipt_key", receipt_key)
  364. for event in receipts:
  365. room_id = event["room_id"]
  366. # exclude room id, as above
  367. event_copy = {k: v for (k, v) in event.iteritems()
  368. if k != "room_id"}
  369. ephemeral_by_room.setdefault(room_id, []).append(event_copy)
  370. defer.returnValue((now_token, ephemeral_by_room))
  371. def full_state_sync_for_archived_room(self, room_id, sync_config,
  372. leave_event_id, leave_token,
  373. timeline_since_token, tags_by_room,
  374. account_data_by_room):
  375. """Sync a room for a client which is starting without any state
  376. Returns:
  377. A Deferred ArchivedSyncResult.
  378. """
  379. return self.incremental_sync_for_archived_room(
  380. sync_config, room_id, leave_event_id, timeline_since_token, tags_by_room,
  381. account_data_by_room, full_state=True, leave_token=leave_token,
  382. )
  383. @defer.inlineCallbacks
  384. def incremental_sync_with_gap(self, sync_config, since_token):
  385. """ Get the incremental delta needed to bring the client up to
  386. date with the server.
  387. Returns:
  388. A Deferred SyncResult.
  389. """
  390. now_token = yield self.event_sources.get_current_token()
  391. rooms = yield self.store.get_rooms_for_user(sync_config.user.to_string())
  392. room_ids = [room.room_id for room in rooms]
  393. presence_source = self.event_sources.sources["presence"]
  394. presence, presence_key = yield presence_source.get_new_events(
  395. user=sync_config.user,
  396. from_key=since_token.presence_key,
  397. limit=sync_config.filter_collection.presence_limit(),
  398. room_ids=room_ids,
  399. is_guest=sync_config.is_guest,
  400. )
  401. now_token = now_token.copy_and_replace("presence_key", presence_key)
  402. now_token, ephemeral_by_room = yield self.ephemeral_by_room(
  403. sync_config, now_token, since_token
  404. )
  405. rm_handler = self.hs.get_handlers().room_member_handler
  406. app_service = yield self.store.get_app_service_by_user_id(
  407. sync_config.user.to_string()
  408. )
  409. if app_service:
  410. rooms = yield self.store.get_app_service_rooms(app_service)
  411. joined_room_ids = set(r.room_id for r in rooms)
  412. else:
  413. joined_room_ids = yield rm_handler.get_joined_rooms_for_user(
  414. sync_config.user
  415. )
  416. user_id = sync_config.user.to_string()
  417. timeline_limit = sync_config.filter_collection.timeline_limit()
  418. tags_by_room = yield self.store.get_updated_tags(
  419. user_id,
  420. since_token.account_data_key,
  421. )
  422. account_data, account_data_by_room = (
  423. yield self.store.get_updated_account_data_for_user(
  424. user_id,
  425. since_token.account_data_key,
  426. )
  427. )
  428. push_rules_changed = yield self.store.have_push_rules_changed_for_user(
  429. user_id, int(since_token.push_rules_key)
  430. )
  431. if push_rules_changed:
  432. account_data["m.push_rules"] = yield self.push_rules_for_user(
  433. sync_config.user
  434. )
  435. # Get a list of membership change events that have happened.
  436. rooms_changed = yield self.store.get_membership_changes_for_user(
  437. user_id, since_token.room_key, now_token.room_key
  438. )
  439. mem_change_events_by_room_id = {}
  440. for event in rooms_changed:
  441. mem_change_events_by_room_id.setdefault(event.room_id, []).append(event)
  442. newly_joined_rooms = []
  443. archived = []
  444. invited = []
  445. for room_id, events in mem_change_events_by_room_id.items():
  446. non_joins = [e for e in events if e.membership != Membership.JOIN]
  447. has_join = len(non_joins) != len(events)
  448. # We want to figure out if we joined the room at some point since
  449. # the last sync (even if we have since left). This is to make sure
  450. # we do send down the room, and with full state, where necessary
  451. if room_id in joined_room_ids or has_join:
  452. old_state = yield self.get_state_at(room_id, since_token)
  453. old_mem_ev = old_state.get((EventTypes.Member, user_id), None)
  454. if not old_mem_ev or old_mem_ev.membership != Membership.JOIN:
  455. newly_joined_rooms.append(room_id)
  456. if room_id in joined_room_ids:
  457. continue
  458. if not non_joins:
  459. continue
  460. # Only bother if we're still currently invited
  461. should_invite = non_joins[-1].membership == Membership.INVITE
  462. if should_invite:
  463. room_sync = InvitedSyncResult(room_id, invite=non_joins[-1])
  464. if room_sync:
  465. invited.append(room_sync)
  466. # Always include leave/ban events. Just take the last one.
  467. # TODO: How do we handle ban -> leave in same batch?
  468. leave_events = [
  469. e for e in non_joins
  470. if e.membership in (Membership.LEAVE, Membership.BAN)
  471. ]
  472. if leave_events:
  473. leave_event = leave_events[-1]
  474. room_sync = yield self.incremental_sync_for_archived_room(
  475. sync_config, room_id, leave_event.event_id, since_token,
  476. tags_by_room, account_data_by_room,
  477. full_state=room_id in newly_joined_rooms
  478. )
  479. if room_sync:
  480. archived.append(room_sync)
  481. # Get all events for rooms we're currently joined to.
  482. room_to_events = yield self.store.get_room_events_stream_for_rooms(
  483. room_ids=joined_room_ids,
  484. from_key=since_token.room_key,
  485. to_key=now_token.room_key,
  486. limit=timeline_limit + 1,
  487. )
  488. joined = []
  489. # We loop through all room ids, even if there are no new events, in case
  490. # there are non room events taht we need to notify about.
  491. for room_id in joined_room_ids:
  492. room_entry = room_to_events.get(room_id, None)
  493. if room_entry:
  494. events, start_key = room_entry
  495. prev_batch_token = now_token.copy_and_replace("room_key", start_key)
  496. newly_joined_room = room_id in newly_joined_rooms
  497. full_state = newly_joined_room
  498. batch = yield self.load_filtered_recents(
  499. room_id, sync_config, prev_batch_token,
  500. since_token=since_token,
  501. recents=events,
  502. newly_joined_room=newly_joined_room,
  503. )
  504. else:
  505. batch = TimelineBatch(
  506. events=[],
  507. prev_batch=since_token,
  508. limited=False,
  509. )
  510. full_state = False
  511. room_sync = yield self.incremental_sync_with_gap_for_room(
  512. room_id=room_id,
  513. sync_config=sync_config,
  514. since_token=since_token,
  515. now_token=now_token,
  516. ephemeral_by_room=ephemeral_by_room,
  517. tags_by_room=tags_by_room,
  518. account_data_by_room=account_data_by_room,
  519. batch=batch,
  520. full_state=full_state,
  521. )
  522. if room_sync:
  523. joined.append(room_sync)
  524. # For each newly joined room, we want to send down presence of
  525. # existing users.
  526. presence_handler = self.hs.get_handlers().presence_handler
  527. extra_presence_users = set()
  528. for room_id in newly_joined_rooms:
  529. users = yield self.store.get_users_in_room(event.room_id)
  530. extra_presence_users.update(users)
  531. # For each new member, send down presence.
  532. for joined_sync in joined:
  533. it = itertools.chain(joined_sync.timeline.events, joined_sync.state.values())
  534. for event in it:
  535. if event.type == EventTypes.Member:
  536. if event.membership == Membership.JOIN:
  537. extra_presence_users.add(event.state_key)
  538. states = yield presence_handler.get_states(
  539. [u for u in extra_presence_users if u != user_id],
  540. as_event=True,
  541. )
  542. presence.extend(states)
  543. account_data_for_user = sync_config.filter_collection.filter_account_data(
  544. self.account_data_for_user(account_data)
  545. )
  546. presence = sync_config.filter_collection.filter_presence(
  547. presence
  548. )
  549. defer.returnValue(SyncResult(
  550. presence=presence,
  551. account_data=account_data_for_user,
  552. joined=joined,
  553. invited=invited,
  554. archived=archived,
  555. next_batch=now_token,
  556. ))
  557. @defer.inlineCallbacks
  558. def load_filtered_recents(self, room_id, sync_config, now_token,
  559. since_token=None, recents=None, newly_joined_room=False):
  560. """
  561. Returns:
  562. a Deferred TimelineBatch
  563. """
  564. with Measure(self.clock, "load_filtered_recents"):
  565. filtering_factor = 2
  566. timeline_limit = sync_config.filter_collection.timeline_limit()
  567. load_limit = max(timeline_limit * filtering_factor, 10)
  568. max_repeat = 5 # Only try a few times per room, otherwise
  569. room_key = now_token.room_key
  570. end_key = room_key
  571. if recents is None or newly_joined_room or timeline_limit < len(recents):
  572. limited = True
  573. else:
  574. limited = False
  575. if recents is not None:
  576. recents = sync_config.filter_collection.filter_room_timeline(recents)
  577. recents = yield self._filter_events_for_client(
  578. sync_config.user.to_string(),
  579. recents,
  580. )
  581. else:
  582. recents = []
  583. since_key = None
  584. if since_token and not newly_joined_room:
  585. since_key = since_token.room_key
  586. while limited and len(recents) < timeline_limit and max_repeat:
  587. events, end_key = yield self.store.get_room_events_stream_for_room(
  588. room_id,
  589. limit=load_limit + 1,
  590. from_key=since_key,
  591. to_key=end_key,
  592. )
  593. loaded_recents = sync_config.filter_collection.filter_room_timeline(
  594. events
  595. )
  596. loaded_recents = yield self._filter_events_for_client(
  597. sync_config.user.to_string(),
  598. loaded_recents,
  599. )
  600. loaded_recents.extend(recents)
  601. recents = loaded_recents
  602. if len(events) <= load_limit:
  603. limited = False
  604. break
  605. max_repeat -= 1
  606. if len(recents) > timeline_limit:
  607. limited = True
  608. recents = recents[-timeline_limit:]
  609. room_key = recents[0].internal_metadata.before
  610. prev_batch_token = now_token.copy_and_replace(
  611. "room_key", room_key
  612. )
  613. defer.returnValue(TimelineBatch(
  614. events=recents,
  615. prev_batch=prev_batch_token,
  616. limited=limited or newly_joined_room
  617. ))
  618. @defer.inlineCallbacks
  619. def incremental_sync_with_gap_for_room(self, room_id, sync_config,
  620. since_token, now_token,
  621. ephemeral_by_room, tags_by_room,
  622. account_data_by_room,
  623. batch, full_state=False):
  624. state = yield self.compute_state_delta(
  625. room_id, batch, sync_config, since_token, now_token,
  626. full_state=full_state
  627. )
  628. account_data = self.account_data_for_room(
  629. room_id, tags_by_room, account_data_by_room
  630. )
  631. account_data = sync_config.filter_collection.filter_room_account_data(
  632. account_data
  633. )
  634. ephemeral = sync_config.filter_collection.filter_room_ephemeral(
  635. ephemeral_by_room.get(room_id, [])
  636. )
  637. unread_notifications = {}
  638. room_sync = JoinedSyncResult(
  639. room_id=room_id,
  640. timeline=batch,
  641. state=state,
  642. ephemeral=ephemeral,
  643. account_data=account_data,
  644. unread_notifications=unread_notifications,
  645. )
  646. if room_sync:
  647. notifs = yield self.unread_notifs_for_room_id(
  648. room_id, sync_config
  649. )
  650. if notifs is not None:
  651. unread_notifications["notification_count"] = notifs["notify_count"]
  652. unread_notifications["highlight_count"] = notifs["highlight_count"]
  653. logger.debug("Room sync: %r", room_sync)
  654. defer.returnValue(room_sync)
  655. @defer.inlineCallbacks
  656. def incremental_sync_for_archived_room(self, sync_config, room_id, leave_event_id,
  657. since_token, tags_by_room,
  658. account_data_by_room, full_state,
  659. leave_token=None):
  660. """ Get the incremental delta needed to bring the client up to date for
  661. the archived room.
  662. Returns:
  663. A Deferred ArchivedSyncResult
  664. """
  665. if not leave_token:
  666. stream_token = yield self.store.get_stream_token_for_event(
  667. leave_event_id
  668. )
  669. leave_token = since_token.copy_and_replace("room_key", stream_token)
  670. if since_token and since_token.is_after(leave_token):
  671. defer.returnValue(None)
  672. batch = yield self.load_filtered_recents(
  673. room_id, sync_config, leave_token, since_token,
  674. )
  675. logger.debug("Recents %r", batch)
  676. state_events_delta = yield self.compute_state_delta(
  677. room_id, batch, sync_config, since_token, leave_token,
  678. full_state=full_state
  679. )
  680. account_data = self.account_data_for_room(
  681. room_id, tags_by_room, account_data_by_room
  682. )
  683. account_data = sync_config.filter_collection.filter_room_account_data(
  684. account_data
  685. )
  686. room_sync = ArchivedSyncResult(
  687. room_id=room_id,
  688. timeline=batch,
  689. state=state_events_delta,
  690. account_data=account_data,
  691. )
  692. logger.debug("Room sync: %r", room_sync)
  693. defer.returnValue(room_sync)
  694. @defer.inlineCallbacks
  695. def get_state_after_event(self, event):
  696. """
  697. Get the room state after the given event
  698. Args:
  699. event(synapse.events.EventBase): event of interest
  700. Returns:
  701. A Deferred map from ((type, state_key)->Event)
  702. """
  703. state = yield self.store.get_state_for_event(event.event_id)
  704. if event.is_state():
  705. state = state.copy()
  706. state[(event.type, event.state_key)] = event
  707. defer.returnValue(state)
  708. @defer.inlineCallbacks
  709. def get_state_at(self, room_id, stream_position):
  710. """ Get the room state at a particular stream position
  711. Args:
  712. room_id(str): room for which to get state
  713. stream_position(StreamToken): point at which to get state
  714. Returns:
  715. A Deferred map from ((type, state_key)->Event)
  716. """
  717. last_events, token = yield self.store.get_recent_events_for_room(
  718. room_id, end_token=stream_position.room_key, limit=1,
  719. )
  720. if last_events:
  721. last_event = last_events[-1]
  722. state = yield self.get_state_after_event(last_event)
  723. else:
  724. # no events in this room - so presumably no state
  725. state = {}
  726. defer.returnValue(state)
  727. @defer.inlineCallbacks
  728. def compute_state_delta(self, room_id, batch, sync_config, since_token, now_token,
  729. full_state):
  730. """ Works out the differnce in state between the start of the timeline
  731. and the previous sync.
  732. Args:
  733. room_id(str):
  734. batch(synapse.handlers.sync.TimelineBatch): The timeline batch for
  735. the room that will be sent to the user.
  736. sync_config(synapse.handlers.sync.SyncConfig):
  737. since_token(str|None): Token of the end of the previous batch. May
  738. be None.
  739. now_token(str): Token of the end of the current batch.
  740. full_state(bool): Whether to force returning the full state.
  741. Returns:
  742. A deferred new event dictionary
  743. """
  744. # TODO(mjark) Check if the state events were received by the server
  745. # after the previous sync, since we need to include those state
  746. # updates even if they occured logically before the previous event.
  747. # TODO(mjark) Check for new redactions in the state events.
  748. with Measure(self.clock, "compute_state_delta"):
  749. if full_state:
  750. if batch:
  751. current_state = yield self.store.get_state_for_event(
  752. batch.events[-1].event_id
  753. )
  754. state = yield self.store.get_state_for_event(
  755. batch.events[0].event_id
  756. )
  757. else:
  758. current_state = yield self.get_state_at(
  759. room_id, stream_position=now_token
  760. )
  761. state = current_state
  762. timeline_state = {
  763. (event.type, event.state_key): event
  764. for event in batch.events if event.is_state()
  765. }
  766. state = _calculate_state(
  767. timeline_contains=timeline_state,
  768. timeline_start=state,
  769. previous={},
  770. current=current_state,
  771. )
  772. elif batch.limited:
  773. state_at_previous_sync = yield self.get_state_at(
  774. room_id, stream_position=since_token
  775. )
  776. current_state = yield self.store.get_state_for_event(
  777. batch.events[-1].event_id
  778. )
  779. state_at_timeline_start = yield self.store.get_state_for_event(
  780. batch.events[0].event_id
  781. )
  782. timeline_state = {
  783. (event.type, event.state_key): event
  784. for event in batch.events if event.is_state()
  785. }
  786. state = _calculate_state(
  787. timeline_contains=timeline_state,
  788. timeline_start=state_at_timeline_start,
  789. previous=state_at_previous_sync,
  790. current=current_state,
  791. )
  792. else:
  793. state = {}
  794. defer.returnValue({
  795. (e.type, e.state_key): e
  796. for e in sync_config.filter_collection.filter_room_state(state.values())
  797. })
  798. def check_joined_room(self, sync_config, state_delta):
  799. """
  800. Check if the user has just joined the given room (so should
  801. be given the full state)
  802. Args:
  803. sync_config(synapse.handlers.sync.SyncConfig):
  804. state_delta(dict[(str,str), synapse.events.FrozenEvent]): the
  805. difference in state since the last sync
  806. Returns:
  807. A deferred Tuple (state_delta, limited)
  808. """
  809. join_event = state_delta.get((
  810. EventTypes.Member, sync_config.user.to_string()), None)
  811. if join_event is not None:
  812. if join_event.content["membership"] == Membership.JOIN:
  813. return True
  814. return False
  815. @defer.inlineCallbacks
  816. def unread_notifs_for_room_id(self, room_id, sync_config):
  817. with Measure(self.clock, "unread_notifs_for_room_id"):
  818. last_unread_event_id = yield self.store.get_last_receipt_event_id_for_user(
  819. user_id=sync_config.user.to_string(),
  820. room_id=room_id,
  821. receipt_type="m.read"
  822. )
  823. notifs = []
  824. if last_unread_event_id:
  825. notifs = yield self.store.get_unread_event_push_actions_by_room_for_user(
  826. room_id, sync_config.user.to_string(), last_unread_event_id
  827. )
  828. defer.returnValue(notifs)
  829. # There is no new information in this period, so your notification
  830. # count is whatever it was last time.
  831. defer.returnValue(None)
  832. def _action_has_highlight(actions):
  833. for action in actions:
  834. try:
  835. if action.get("set_tweak", None) == "highlight":
  836. return action.get("value", True)
  837. except AttributeError:
  838. pass
  839. return False
  840. def _calculate_state(timeline_contains, timeline_start, previous, current):
  841. """Works out what state to include in a sync response.
  842. Args:
  843. timeline_contains (dict): state in the timeline
  844. timeline_start (dict): state at the start of the timeline
  845. previous (dict): state at the end of the previous sync (or empty dict
  846. if this is an initial sync)
  847. current (dict): state at the end of the timeline
  848. Returns:
  849. dict
  850. """
  851. event_id_to_state = {
  852. e.event_id: e
  853. for e in itertools.chain(
  854. timeline_contains.values(),
  855. previous.values(),
  856. timeline_start.values(),
  857. current.values(),
  858. )
  859. }
  860. c_ids = set(e.event_id for e in current.values())
  861. tc_ids = set(e.event_id for e in timeline_contains.values())
  862. p_ids = set(e.event_id for e in previous.values())
  863. ts_ids = set(e.event_id for e in timeline_start.values())
  864. state_ids = ((c_ids | ts_ids) - p_ids) - tc_ids
  865. evs = (event_id_to_state[e] for e in state_ids)
  866. return {
  867. (e.type, e.state_key): e
  868. for e in evs
  869. }