resource.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015 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 synapse.http.servlet import parse_integer, parse_string
  16. from synapse.http.server import request_handler, finish_request
  17. from twisted.web.resource import Resource
  18. from twisted.web.server import NOT_DONE_YET
  19. from twisted.internet import defer
  20. import ujson as json
  21. import collections
  22. import logging
  23. logger = logging.getLogger(__name__)
  24. REPLICATION_PREFIX = "/_synapse/replication"
  25. STREAM_NAMES = (
  26. ("events",),
  27. ("presence",),
  28. ("typing",),
  29. ("receipts",),
  30. ("user_account_data", "room_account_data", "tag_account_data",),
  31. ("backfill",),
  32. ("push_rules",),
  33. ("pushers",),
  34. ("state",),
  35. )
  36. class ReplicationResource(Resource):
  37. """
  38. HTTP endpoint for extracting data from synapse.
  39. The streams of data returned by the endpoint are controlled by the
  40. parameters given to the API. To return a given stream pass a query
  41. parameter with a position in the stream to return data from or the
  42. special value "-1" to return data from the start of the stream.
  43. If there is no data for any of the supplied streams after the given
  44. position then the request will block until there is data for one
  45. of the streams. This allows clients to long-poll this API.
  46. The possible streams are:
  47. * "streams": A special stream returing the positions of other streams.
  48. * "events": The new events seen on the server.
  49. * "presence": Presence updates.
  50. * "typing": Typing updates.
  51. * "receipts": Receipt updates.
  52. * "user_account_data": Top-level per user account data.
  53. * "room_account_data: Per room per user account data.
  54. * "tag_account_data": Per room per user tags.
  55. * "backfill": Old events that have been backfilled from other servers.
  56. * "push_rules": Per user changes to push rules.
  57. * "pushers": Per user changes to their pushers.
  58. The API takes two additional query parameters:
  59. * "timeout": How long to wait before returning an empty response.
  60. * "limit": The maximum number of rows to return for the selected streams.
  61. The response is a JSON object with keys for each stream with updates. Under
  62. each key is a JSON object with:
  63. * "position": The current position of the stream.
  64. * "field_names": The names of the fields in each row.
  65. * "rows": The updates as an array of arrays.
  66. There are a number of ways this API could be used:
  67. 1) To replicate the contents of the backing database to another database.
  68. 2) To be notified when the contents of a shared backing database changes.
  69. 3) To "tail" the activity happening on a server for debugging.
  70. In the first case the client would track all of the streams and store it's
  71. own copy of the data.
  72. In the second case the client might theoretically just be able to follow
  73. the "streams" stream to track where the other streams are. However in
  74. practise it will probably need to get the contents of the streams in
  75. order to expire the any in-memory caches. Whether it gets the contents
  76. of the streams from this replication API or directly from the backing
  77. store is a matter of taste.
  78. In the third case the client would use the "streams" stream to find what
  79. streams are available and their current positions. Then it can start
  80. long-polling this replication API for new data on those streams.
  81. """
  82. isLeaf = True
  83. def __init__(self, hs):
  84. Resource.__init__(self) # Resource is old-style, so no super()
  85. self.version_string = hs.version_string
  86. self.store = hs.get_datastore()
  87. self.sources = hs.get_event_sources()
  88. self.presence_handler = hs.get_handlers().presence_handler
  89. self.typing_handler = hs.get_handlers().typing_notification_handler
  90. self.notifier = hs.notifier
  91. def render_GET(self, request):
  92. self._async_render_GET(request)
  93. return NOT_DONE_YET
  94. @defer.inlineCallbacks
  95. def current_replication_token(self):
  96. stream_token = yield self.sources.get_current_token()
  97. backfill_token = yield self.store.get_current_backfill_token()
  98. push_rules_token, room_stream_token = self.store.get_push_rules_stream_token()
  99. pushers_token = self.store.get_pushers_stream_token()
  100. state_token = self.store.get_state_stream_token()
  101. defer.returnValue(_ReplicationToken(
  102. room_stream_token,
  103. int(stream_token.presence_key),
  104. int(stream_token.typing_key),
  105. int(stream_token.receipt_key),
  106. int(stream_token.account_data_key),
  107. backfill_token,
  108. push_rules_token,
  109. pushers_token,
  110. state_token,
  111. ))
  112. @request_handler
  113. @defer.inlineCallbacks
  114. def _async_render_GET(self, request):
  115. limit = parse_integer(request, "limit", 100)
  116. timeout = parse_integer(request, "timeout", 10 * 1000)
  117. request.setHeader(b"Content-Type", b"application/json")
  118. request_streams = {
  119. name: parse_integer(request, name)
  120. for names in STREAM_NAMES for name in names
  121. }
  122. request_streams["streams"] = parse_string(request, "streams")
  123. def replicate():
  124. return self.replicate(request_streams, limit)
  125. result = yield self.notifier.wait_for_replication(replicate, timeout)
  126. request.write(json.dumps(result, ensure_ascii=False))
  127. finish_request(request)
  128. @defer.inlineCallbacks
  129. def replicate(self, request_streams, limit):
  130. writer = _Writer()
  131. current_token = yield self.current_replication_token()
  132. logger.info("Replicating up to %r", current_token)
  133. yield self.account_data(writer, current_token, limit, request_streams)
  134. yield self.events(writer, current_token, limit, request_streams)
  135. # TODO: implement limit
  136. yield self.presence(writer, current_token, request_streams)
  137. yield self.typing(writer, current_token, request_streams)
  138. yield self.receipts(writer, current_token, limit, request_streams)
  139. yield self.push_rules(writer, current_token, limit, request_streams)
  140. yield self.pushers(writer, current_token, limit, request_streams)
  141. yield self.state(writer, current_token, limit, request_streams)
  142. self.streams(writer, current_token, request_streams)
  143. logger.info("Replicated %d rows", writer.total)
  144. defer.returnValue(writer.finish())
  145. def streams(self, writer, current_token, request_streams):
  146. request_token = request_streams.get("streams")
  147. streams = []
  148. if request_token is not None:
  149. if request_token == "-1":
  150. for names, position in zip(STREAM_NAMES, current_token):
  151. streams.extend((name, position) for name in names)
  152. else:
  153. items = zip(
  154. STREAM_NAMES,
  155. current_token,
  156. _ReplicationToken(request_token)
  157. )
  158. for names, current_id, last_id in items:
  159. if last_id < current_id:
  160. streams.extend((name, current_id) for name in names)
  161. if streams:
  162. writer.write_header_and_rows(
  163. "streams", streams, ("name", "position"),
  164. position=str(current_token)
  165. )
  166. @defer.inlineCallbacks
  167. def events(self, writer, current_token, limit, request_streams):
  168. request_events = request_streams.get("events")
  169. request_backfill = request_streams.get("backfill")
  170. if request_events is not None or request_backfill is not None:
  171. if request_events is None:
  172. request_events = current_token.events
  173. if request_backfill is None:
  174. request_backfill = current_token.backfill
  175. res = yield self.store.get_all_new_events(
  176. request_backfill, request_events,
  177. current_token.backfill, current_token.events,
  178. limit
  179. )
  180. writer.write_header_and_rows("events", res.new_forward_events, (
  181. "position", "internal", "json", "state_group"
  182. ))
  183. writer.write_header_and_rows("backfill", res.new_backfill_events, (
  184. "position", "internal", "json", "state_group"
  185. ))
  186. writer.write_header_and_rows(
  187. "forward_ex_outliers", res.forward_ex_outliers,
  188. ("position", "event_id", "state_group")
  189. )
  190. writer.write_header_and_rows(
  191. "backward_ex_outliers", res.backward_ex_outliers,
  192. ("position", "event_id", "state_group")
  193. )
  194. writer.write_header_and_rows(
  195. "state_resets", res.state_resets, ("position",)
  196. )
  197. @defer.inlineCallbacks
  198. def presence(self, writer, current_token, request_streams):
  199. current_position = current_token.presence
  200. request_presence = request_streams.get("presence")
  201. if request_presence is not None:
  202. presence_rows = yield self.presence_handler.get_all_presence_updates(
  203. request_presence, current_position
  204. )
  205. writer.write_header_and_rows("presence", presence_rows, (
  206. "position", "user_id", "state", "last_active_ts",
  207. "last_federation_update_ts", "last_user_sync_ts",
  208. "status_msg", "currently_active",
  209. ))
  210. @defer.inlineCallbacks
  211. def typing(self, writer, current_token, request_streams):
  212. current_position = current_token.presence
  213. request_typing = request_streams.get("typing")
  214. if request_typing is not None:
  215. typing_rows = yield self.typing_handler.get_all_typing_updates(
  216. request_typing, current_position
  217. )
  218. writer.write_header_and_rows("typing", typing_rows, (
  219. "position", "room_id", "typing"
  220. ))
  221. @defer.inlineCallbacks
  222. def receipts(self, writer, current_token, limit, request_streams):
  223. current_position = current_token.receipts
  224. request_receipts = request_streams.get("receipts")
  225. if request_receipts is not None:
  226. receipts_rows = yield self.store.get_all_updated_receipts(
  227. request_receipts, current_position, limit
  228. )
  229. writer.write_header_and_rows("receipts", receipts_rows, (
  230. "position", "room_id", "receipt_type", "user_id", "event_id", "data"
  231. ))
  232. @defer.inlineCallbacks
  233. def account_data(self, writer, current_token, limit, request_streams):
  234. current_position = current_token.account_data
  235. user_account_data = request_streams.get("user_account_data")
  236. room_account_data = request_streams.get("room_account_data")
  237. tag_account_data = request_streams.get("tag_account_data")
  238. if user_account_data is not None or room_account_data is not None:
  239. if user_account_data is None:
  240. user_account_data = current_position
  241. if room_account_data is None:
  242. room_account_data = current_position
  243. user_rows, room_rows = yield self.store.get_all_updated_account_data(
  244. user_account_data, room_account_data, current_position, limit
  245. )
  246. writer.write_header_and_rows("user_account_data", user_rows, (
  247. "position", "user_id", "type", "content"
  248. ))
  249. writer.write_header_and_rows("room_account_data", room_rows, (
  250. "position", "user_id", "room_id", "type", "content"
  251. ))
  252. if tag_account_data is not None:
  253. tag_rows = yield self.store.get_all_updated_tags(
  254. tag_account_data, current_position, limit
  255. )
  256. writer.write_header_and_rows("tag_account_data", tag_rows, (
  257. "position", "user_id", "room_id", "tags"
  258. ))
  259. @defer.inlineCallbacks
  260. def push_rules(self, writer, current_token, limit, request_streams):
  261. current_position = current_token.push_rules
  262. push_rules = request_streams.get("push_rules")
  263. if push_rules is not None:
  264. rows = yield self.store.get_all_push_rule_updates(
  265. push_rules, current_position, limit
  266. )
  267. writer.write_header_and_rows("push_rules", rows, (
  268. "position", "event_stream_ordering", "user_id", "rule_id", "op",
  269. "priority_class", "priority", "conditions", "actions"
  270. ))
  271. @defer.inlineCallbacks
  272. def pushers(self, writer, current_token, limit, request_streams):
  273. current_position = current_token.pushers
  274. pushers = request_streams.get("pushers")
  275. if pushers is not None:
  276. updated, deleted = yield self.store.get_all_updated_pushers(
  277. pushers, current_position, limit
  278. )
  279. writer.write_header_and_rows("pushers", updated, (
  280. "position", "user_id", "access_token", "profile_tag", "kind",
  281. "app_id", "app_display_name", "device_display_name", "pushkey",
  282. "ts", "lang", "data"
  283. ))
  284. writer.write_header_and_rows("deleted", deleted, (
  285. "position", "user_id", "app_id", "pushkey"
  286. ))
  287. @defer.inlineCallbacks
  288. def state(self, writer, current_token, limit, request_streams):
  289. current_position = current_token.state
  290. state = request_streams.get("state")
  291. if state is not None:
  292. state_groups, state_group_state = (
  293. yield self.store.get_all_new_state_groups(
  294. state, current_position, limit
  295. )
  296. )
  297. writer.write_header_and_rows("state_groups", state_groups, (
  298. "position", "room_id", "event_id"
  299. ))
  300. writer.write_header_and_rows("state_group_state", state_group_state, (
  301. "position", "type", "state_key", "event_id"
  302. ))
  303. class _Writer(object):
  304. """Writes the streams as a JSON object as the response to the request"""
  305. def __init__(self):
  306. self.streams = {}
  307. self.total = 0
  308. def write_header_and_rows(self, name, rows, fields, position=None):
  309. if not rows:
  310. return
  311. if position is None:
  312. position = rows[-1][0]
  313. self.streams[name] = {
  314. "position": str(position),
  315. "field_names": fields,
  316. "rows": rows,
  317. }
  318. self.total += len(rows)
  319. def finish(self):
  320. return self.streams
  321. class _ReplicationToken(collections.namedtuple("_ReplicationToken", (
  322. "events", "presence", "typing", "receipts", "account_data", "backfill",
  323. "push_rules", "pushers", "state"
  324. ))):
  325. __slots__ = []
  326. def __new__(cls, *args):
  327. if len(args) == 1:
  328. streams = [int(value) for value in args[0].split("_")]
  329. if len(streams) < len(cls._fields):
  330. streams.extend([0] * (len(cls._fields) - len(streams)))
  331. return cls(*streams)
  332. else:
  333. return super(_ReplicationToken, cls).__new__(cls, *args)
  334. def __str__(self):
  335. return "_".join(str(value) for value in self)