Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

584 righe
20 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from enum import Enum
  16. from typing import TYPE_CHECKING, Iterable, List, Mapping, Optional, Tuple, cast
  17. import attr
  18. from canonicaljson import encode_canonical_json
  19. from synapse.api.constants import Direction
  20. from synapse.metrics.background_process_metrics import wrap_as_background_process
  21. from synapse.storage._base import db_to_json
  22. from synapse.storage.database import (
  23. DatabasePool,
  24. LoggingDatabaseConnection,
  25. LoggingTransaction,
  26. )
  27. from synapse.storage.databases.main.cache import CacheInvalidationWorkerStore
  28. from synapse.types import JsonDict, StrCollection
  29. from synapse.util.caches.descriptors import cached, cachedList
  30. if TYPE_CHECKING:
  31. from synapse.server import HomeServer
  32. db_binary_type = memoryview
  33. logger = logging.getLogger(__name__)
  34. class DestinationSortOrder(Enum):
  35. """Enum to define the sorting method used when returning destinations."""
  36. DESTINATION = "destination"
  37. RETRY_LAST_TS = "retry_last_ts"
  38. RETTRY_INTERVAL = "retry_interval"
  39. FAILURE_TS = "failure_ts"
  40. LAST_SUCCESSFUL_STREAM_ORDERING = "last_successful_stream_ordering"
  41. @attr.s(slots=True, frozen=True, auto_attribs=True)
  42. class DestinationRetryTimings:
  43. """The current destination retry timing info for a remote server."""
  44. # The first time we tried and failed to reach the remote server, in ms.
  45. failure_ts: int
  46. # The last time we tried and failed to reach the remote server, in ms.
  47. retry_last_ts: int
  48. # How long since the last time we tried to reach the remote server before
  49. # trying again, in ms.
  50. retry_interval: int
  51. class TransactionWorkerStore(CacheInvalidationWorkerStore):
  52. def __init__(
  53. self,
  54. database: DatabasePool,
  55. db_conn: LoggingDatabaseConnection,
  56. hs: "HomeServer",
  57. ):
  58. super().__init__(database, db_conn, hs)
  59. if hs.config.worker.run_background_tasks:
  60. self._clock.looping_call(self._cleanup_transactions, 30 * 60 * 1000)
  61. @wrap_as_background_process("cleanup_transactions")
  62. async def _cleanup_transactions(self) -> None:
  63. now = self._clock.time_msec()
  64. month_ago = now - 30 * 24 * 60 * 60 * 1000
  65. def _cleanup_transactions_txn(txn: LoggingTransaction) -> None:
  66. txn.execute("DELETE FROM received_transactions WHERE ts < ?", (month_ago,))
  67. await self.db_pool.runInteraction(
  68. "_cleanup_transactions", _cleanup_transactions_txn
  69. )
  70. async def get_received_txn_response(
  71. self, transaction_id: str, origin: str
  72. ) -> Optional[Tuple[int, JsonDict]]:
  73. """For an incoming transaction from a given origin, check if we have
  74. already responded to it. If so, return the response code and response
  75. body (as a dict).
  76. Args:
  77. transaction_id
  78. origin
  79. Returns:
  80. None if we have not previously responded to this transaction or a
  81. 2-tuple of (int, dict)
  82. """
  83. return await self.db_pool.runInteraction(
  84. "get_received_txn_response",
  85. self._get_received_txn_response,
  86. transaction_id,
  87. origin,
  88. )
  89. def _get_received_txn_response(
  90. self, txn: LoggingTransaction, transaction_id: str, origin: str
  91. ) -> Optional[Tuple[int, JsonDict]]:
  92. result = self.db_pool.simple_select_one_txn(
  93. txn,
  94. table="received_transactions",
  95. keyvalues={"transaction_id": transaction_id, "origin": origin},
  96. retcols=(
  97. "transaction_id",
  98. "origin",
  99. "ts",
  100. "response_code",
  101. "response_json",
  102. "has_been_referenced",
  103. ),
  104. allow_none=True,
  105. )
  106. if result and result["response_code"]:
  107. return result["response_code"], db_to_json(result["response_json"])
  108. else:
  109. return None
  110. async def set_received_txn_response(
  111. self, transaction_id: str, origin: str, code: int, response_dict: JsonDict
  112. ) -> None:
  113. """Persist the response we returned for an incoming transaction, and
  114. should return for subsequent transactions with the same transaction_id
  115. and origin.
  116. Args:
  117. transaction_id: The incoming transaction ID.
  118. origin: The origin server.
  119. code: The response code.
  120. response_dict: The response, to be encoded into JSON.
  121. """
  122. await self.db_pool.simple_upsert(
  123. table="received_transactions",
  124. keyvalues={
  125. "transaction_id": transaction_id,
  126. "origin": origin,
  127. },
  128. values={},
  129. insertion_values={
  130. "response_code": code,
  131. "response_json": db_binary_type(encode_canonical_json(response_dict)),
  132. "ts": self._clock.time_msec(),
  133. },
  134. desc="set_received_txn_response",
  135. )
  136. @cached(max_entries=10000)
  137. async def get_destination_retry_timings(
  138. self,
  139. destination: str,
  140. ) -> Optional[DestinationRetryTimings]:
  141. """Gets the current retry timings (if any) for a given destination.
  142. Args:
  143. destination (str)
  144. Returns:
  145. None if not retrying
  146. Otherwise a dict for the retry scheme
  147. """
  148. result = await self.db_pool.runInteraction(
  149. "get_destination_retry_timings",
  150. self._get_destination_retry_timings,
  151. destination,
  152. )
  153. return result
  154. def _get_destination_retry_timings(
  155. self, txn: LoggingTransaction, destination: str
  156. ) -> Optional[DestinationRetryTimings]:
  157. result = self.db_pool.simple_select_one_txn(
  158. txn,
  159. table="destinations",
  160. keyvalues={"destination": destination},
  161. retcols=("failure_ts", "retry_last_ts", "retry_interval"),
  162. allow_none=True,
  163. )
  164. # check we have a row and retry_last_ts is not null or zero
  165. # (retry_last_ts can't be negative)
  166. if result and result["retry_last_ts"]:
  167. return DestinationRetryTimings(**result)
  168. else:
  169. return None
  170. @cachedList(
  171. cached_method_name="get_destination_retry_timings", list_name="destinations"
  172. )
  173. async def get_destination_retry_timings_batch(
  174. self, destinations: StrCollection
  175. ) -> Mapping[str, Optional[DestinationRetryTimings]]:
  176. rows = await self.db_pool.simple_select_many_batch(
  177. table="destinations",
  178. iterable=destinations,
  179. column="destination",
  180. retcols=("destination", "failure_ts", "retry_last_ts", "retry_interval"),
  181. desc="get_destination_retry_timings_batch",
  182. )
  183. return {
  184. row.pop("destination"): DestinationRetryTimings(**row)
  185. for row in rows
  186. if row["retry_last_ts"] and row["failure_ts"] and row["retry_interval"]
  187. }
  188. async def set_destination_retry_timings(
  189. self,
  190. destination: str,
  191. failure_ts: Optional[int],
  192. retry_last_ts: int,
  193. retry_interval: int,
  194. ) -> None:
  195. """Sets the current retry timings for a given destination.
  196. Both timings should be zero if retrying is no longer occurring.
  197. Args:
  198. destination
  199. failure_ts: when the server started failing (ms since epoch)
  200. retry_last_ts: time of last retry attempt in unix epoch ms
  201. retry_interval: how long until next retry in ms
  202. """
  203. await self.db_pool.runInteraction(
  204. "set_destination_retry_timings",
  205. self._set_destination_retry_timings_txn,
  206. destination,
  207. failure_ts,
  208. retry_last_ts,
  209. retry_interval,
  210. db_autocommit=True, # Safe as it's a single upsert
  211. )
  212. def _set_destination_retry_timings_txn(
  213. self,
  214. txn: LoggingTransaction,
  215. destination: str,
  216. failure_ts: Optional[int],
  217. retry_last_ts: int,
  218. retry_interval: int,
  219. ) -> None:
  220. # Upsert retry time interval if retry_interval is zero (i.e. we're
  221. # resetting it) or greater than the existing retry interval.
  222. #
  223. # WARNING: This is executed in autocommit, so we shouldn't add any more
  224. # SQL calls in here (without being very careful).
  225. sql = """
  226. INSERT INTO destinations (
  227. destination, failure_ts, retry_last_ts, retry_interval
  228. )
  229. VALUES (?, ?, ?, ?)
  230. ON CONFLICT (destination) DO UPDATE SET
  231. failure_ts = EXCLUDED.failure_ts,
  232. retry_last_ts = EXCLUDED.retry_last_ts,
  233. retry_interval = EXCLUDED.retry_interval
  234. WHERE
  235. EXCLUDED.retry_interval = 0
  236. OR EXCLUDED.retry_last_ts = 0
  237. OR destinations.retry_interval IS NULL
  238. OR destinations.retry_interval < EXCLUDED.retry_interval
  239. OR destinations.retry_last_ts < EXCLUDED.retry_last_ts
  240. """
  241. txn.execute(sql, (destination, failure_ts, retry_last_ts, retry_interval))
  242. self._invalidate_cache_and_stream(
  243. txn, self.get_destination_retry_timings, (destination,)
  244. )
  245. async def store_destination_rooms_entries(
  246. self,
  247. destinations: Iterable[str],
  248. room_id: str,
  249. stream_ordering: int,
  250. ) -> None:
  251. """
  252. Updates or creates `destination_rooms` entries in batch for a single event.
  253. Args:
  254. destinations: list of destinations
  255. room_id: the room_id of the event
  256. stream_ordering: the stream_ordering of the event
  257. """
  258. await self.db_pool.simple_upsert_many(
  259. table="destinations",
  260. key_names=("destination",),
  261. key_values=[(d,) for d in destinations],
  262. value_names=[],
  263. value_values=[],
  264. desc="store_destination_rooms_entries_dests",
  265. )
  266. rows = [(destination, room_id) for destination in destinations]
  267. await self.db_pool.simple_upsert_many(
  268. table="destination_rooms",
  269. key_names=("destination", "room_id"),
  270. key_values=rows,
  271. value_names=["stream_ordering"],
  272. value_values=[(stream_ordering,)] * len(rows),
  273. desc="store_destination_rooms_entries_rooms",
  274. )
  275. async def get_destination_last_successful_stream_ordering(
  276. self, destination: str
  277. ) -> Optional[int]:
  278. """
  279. Gets the stream ordering of the PDU most-recently successfully sent
  280. to the specified destination, or None if this information has not been
  281. tracked yet.
  282. Args:
  283. destination: the destination to query
  284. """
  285. return await self.db_pool.simple_select_one_onecol(
  286. "destinations",
  287. {"destination": destination},
  288. "last_successful_stream_ordering",
  289. allow_none=True,
  290. desc="get_last_successful_stream_ordering",
  291. )
  292. async def set_destination_last_successful_stream_ordering(
  293. self, destination: str, last_successful_stream_ordering: int
  294. ) -> None:
  295. """
  296. Marks that we have successfully sent the PDUs up to and including the
  297. one specified.
  298. Args:
  299. destination: the destination we have successfully sent to
  300. last_successful_stream_ordering: the stream_ordering of the most
  301. recent successfully-sent PDU
  302. """
  303. await self.db_pool.simple_upsert(
  304. "destinations",
  305. keyvalues={"destination": destination},
  306. values={"last_successful_stream_ordering": last_successful_stream_ordering},
  307. desc="set_last_successful_stream_ordering",
  308. )
  309. async def get_catch_up_room_event_ids(
  310. self,
  311. destination: str,
  312. last_successful_stream_ordering: int,
  313. ) -> List[str]:
  314. """
  315. Returns at most 50 event IDs and their corresponding stream_orderings
  316. that correspond to the oldest events that have not yet been sent to
  317. the destination.
  318. Args:
  319. destination: the destination in question
  320. last_successful_stream_ordering: the stream_ordering of the
  321. most-recently successfully-transmitted event to the destination
  322. Returns:
  323. list of event_ids
  324. """
  325. return await self.db_pool.runInteraction(
  326. "get_catch_up_room_event_ids",
  327. self._get_catch_up_room_event_ids_txn,
  328. destination,
  329. last_successful_stream_ordering,
  330. )
  331. @staticmethod
  332. def _get_catch_up_room_event_ids_txn(
  333. txn: LoggingTransaction,
  334. destination: str,
  335. last_successful_stream_ordering: int,
  336. ) -> List[str]:
  337. q = """
  338. SELECT event_id FROM destination_rooms
  339. JOIN events USING (stream_ordering)
  340. WHERE destination = ?
  341. AND stream_ordering > ?
  342. ORDER BY stream_ordering
  343. LIMIT 50
  344. """
  345. txn.execute(
  346. q,
  347. (destination, last_successful_stream_ordering),
  348. )
  349. event_ids = [row[0] for row in txn]
  350. return event_ids
  351. async def get_catch_up_outstanding_destinations(
  352. self, after_destination: Optional[str]
  353. ) -> List[str]:
  354. """
  355. Gets at most 25 destinations which have outstanding PDUs to be caught up,
  356. and are not being backed off from
  357. Args:
  358. after_destination:
  359. If provided, all destinations must be lexicographically greater
  360. than this one.
  361. Returns:
  362. list of up to 25 destinations with outstanding catch-up.
  363. These are the lexicographically first destinations which are
  364. lexicographically greater than after_destination (if provided).
  365. """
  366. time = self.hs.get_clock().time_msec()
  367. return await self.db_pool.runInteraction(
  368. "get_catch_up_outstanding_destinations",
  369. self._get_catch_up_outstanding_destinations_txn,
  370. time,
  371. after_destination,
  372. )
  373. @staticmethod
  374. def _get_catch_up_outstanding_destinations_txn(
  375. txn: LoggingTransaction, now_time_ms: int, after_destination: Optional[str]
  376. ) -> List[str]:
  377. q = """
  378. SELECT DISTINCT destination FROM destinations
  379. INNER JOIN destination_rooms USING (destination)
  380. WHERE
  381. stream_ordering > last_successful_stream_ordering
  382. AND destination > ?
  383. AND (
  384. retry_last_ts IS NULL OR
  385. retry_last_ts + retry_interval < ?
  386. )
  387. ORDER BY destination
  388. LIMIT 25
  389. """
  390. txn.execute(
  391. q,
  392. (
  393. # everything is lexicographically greater than "" so this gives
  394. # us the first batch of up to 25.
  395. after_destination or "",
  396. now_time_ms,
  397. ),
  398. )
  399. destinations = [row[0] for row in txn]
  400. return destinations
  401. async def get_destinations_paginate(
  402. self,
  403. start: int,
  404. limit: int,
  405. destination: Optional[str] = None,
  406. order_by: str = DestinationSortOrder.DESTINATION.value,
  407. direction: Direction = Direction.FORWARDS,
  408. ) -> Tuple[List[JsonDict], int]:
  409. """Function to retrieve a paginated list of destinations.
  410. This will return a json list of destinations and the
  411. total number of destinations matching the filter criteria.
  412. Args:
  413. start: start number to begin the query from
  414. limit: number of rows to retrieve
  415. destination: search string in destination
  416. order_by: the sort order of the returned list
  417. direction: sort ascending or descending
  418. Returns:
  419. A tuple of a list of mappings from destination to information
  420. and a count of total destinations.
  421. """
  422. def get_destinations_paginate_txn(
  423. txn: LoggingTransaction,
  424. ) -> Tuple[List[JsonDict], int]:
  425. order_by_column = DestinationSortOrder(order_by).value
  426. if direction == Direction.BACKWARDS:
  427. order = "DESC"
  428. else:
  429. order = "ASC"
  430. args: List[object] = []
  431. where_statement = ""
  432. if destination:
  433. args.extend(["%" + destination.lower() + "%"])
  434. where_statement = "WHERE LOWER(destination) LIKE ?"
  435. sql_base = f"FROM destinations {where_statement} "
  436. sql = f"SELECT COUNT(*) as total_destinations {sql_base}"
  437. txn.execute(sql, args)
  438. count = cast(Tuple[int], txn.fetchone())[0]
  439. sql = f"""
  440. SELECT destination, retry_last_ts, retry_interval, failure_ts,
  441. last_successful_stream_ordering
  442. {sql_base}
  443. ORDER BY {order_by_column} {order}, destination ASC
  444. LIMIT ? OFFSET ?
  445. """
  446. txn.execute(sql, args + [limit, start])
  447. destinations = self.db_pool.cursor_to_dict(txn)
  448. return destinations, count
  449. return await self.db_pool.runInteraction(
  450. "get_destinations_paginate_txn", get_destinations_paginate_txn
  451. )
  452. async def get_destination_rooms_paginate(
  453. self,
  454. destination: str,
  455. start: int,
  456. limit: int,
  457. direction: Direction = Direction.FORWARDS,
  458. ) -> Tuple[List[JsonDict], int]:
  459. """Function to retrieve a paginated list of destination's rooms.
  460. This will return a json list of rooms and the
  461. total number of rooms.
  462. Args:
  463. destination: the destination to query
  464. start: start number to begin the query from
  465. limit: number of rows to retrieve
  466. direction: sort ascending or descending by room_id
  467. Returns:
  468. A tuple of a dict of rooms and a count of total rooms.
  469. """
  470. def get_destination_rooms_paginate_txn(
  471. txn: LoggingTransaction,
  472. ) -> Tuple[List[JsonDict], int]:
  473. if direction == Direction.BACKWARDS:
  474. order = "DESC"
  475. else:
  476. order = "ASC"
  477. sql = """
  478. SELECT COUNT(*) as total_rooms
  479. FROM destination_rooms
  480. WHERE destination = ?
  481. """
  482. txn.execute(sql, [destination])
  483. count = cast(Tuple[int], txn.fetchone())[0]
  484. rooms = self.db_pool.simple_select_list_paginate_txn(
  485. txn=txn,
  486. table="destination_rooms",
  487. orderby="room_id",
  488. start=start,
  489. limit=limit,
  490. retcols=("room_id", "stream_ordering"),
  491. order_direction=order,
  492. )
  493. return rooms, count
  494. return await self.db_pool.runInteraction(
  495. "get_destination_rooms_paginate_txn", get_destination_rooms_paginate_txn
  496. )
  497. async def is_destination_known(self, destination: str) -> bool:
  498. """Check if a destination is known to the server."""
  499. result = await self.db_pool.simple_select_one_onecol(
  500. table="destinations",
  501. keyvalues={"destination": destination},
  502. retcol="1",
  503. allow_none=True,
  504. desc="is_destination_known",
  505. )
  506. return bool(result)