test_monthly_active_users.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. # Copyright 2018 New Vector
  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. from typing import Any, Dict, List
  15. from unittest.mock import Mock
  16. from twisted.test.proto_helpers import MemoryReactor
  17. from synapse.api.constants import UserTypes
  18. from synapse.server import HomeServer
  19. from synapse.util import Clock
  20. from tests import unittest
  21. from tests.test_utils import make_awaitable
  22. from tests.unittest import default_config, override_config
  23. FORTY_DAYS = 40 * 24 * 60 * 60
  24. def gen_3pids(count: int) -> List[Dict[str, Any]]:
  25. """Generate `count` threepids as a list."""
  26. return [
  27. {"medium": "email", "address": "user%i@matrix.org" % i} for i in range(count)
  28. ]
  29. class MonthlyActiveUsersTestCase(unittest.HomeserverTestCase):
  30. def default_config(self) -> Dict[str, Any]:
  31. config = default_config("test")
  32. config.update({"limit_usage_by_mau": True, "max_mau_value": 50})
  33. # apply any additional config which was specified via the override_config
  34. # decorator.
  35. if self._extra_config is not None:
  36. config.update(self._extra_config)
  37. return config
  38. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  39. self.store = hs.get_datastores().main
  40. # Advance the clock a bit
  41. self.reactor.advance(FORTY_DAYS)
  42. @override_config({"max_mau_value": 3, "mau_limit_reserved_threepids": gen_3pids(3)})
  43. def test_initialise_reserved_users(self):
  44. threepids = self.hs.config.server.mau_limits_reserved_threepids
  45. # register three users, of which two have reserved 3pids, and a third
  46. # which is a support user.
  47. user1 = "@user1:server"
  48. user1_email = threepids[0]["address"]
  49. user2 = "@user2:server"
  50. user2_email = threepids[1]["address"]
  51. user3 = "@user3:server"
  52. self.get_success(self.store.register_user(user_id=user1))
  53. self.get_success(self.store.register_user(user_id=user2))
  54. self.get_success(
  55. self.store.register_user(user_id=user3, user_type=UserTypes.SUPPORT)
  56. )
  57. now = int(self.hs.get_clock().time_msec())
  58. self.get_success(
  59. self.store.user_add_threepid(user1, "email", user1_email, now, now)
  60. )
  61. self.get_success(
  62. self.store.user_add_threepid(user2, "email", user2_email, now, now)
  63. )
  64. # XXX why are we doing this here? this function is only run at startup
  65. # so it is odd to re-run it here.
  66. self.get_success(
  67. self.store.db_pool.runInteraction(
  68. "initialise", self.store._initialise_reserved_users, threepids
  69. )
  70. )
  71. # the number of users we expect will be counted against the mau limit
  72. # -1 because user3 is a support user and does not count
  73. user_num = len(threepids) - 1
  74. # Check the number of active users. Ensure user3 (support user) is not counted
  75. active_count = self.get_success(self.store.get_monthly_active_count())
  76. self.assertEqual(active_count, user_num)
  77. # Test each of the registered users is marked as active
  78. timestamp = self.get_success(self.store.user_last_seen_monthly_active(user1))
  79. self.assertGreater(timestamp, 0)
  80. timestamp = self.get_success(self.store.user_last_seen_monthly_active(user2))
  81. self.assertGreater(timestamp, 0)
  82. # Test that users with reserved 3pids are not removed from the MAU table
  83. # XXX some of this is redundant. poking things into the config shouldn't
  84. # work, and in any case it's not obvious what we expect to happen when
  85. # we advance the reactor.
  86. self.hs.config.server.max_mau_value = 0
  87. self.reactor.advance(FORTY_DAYS)
  88. self.hs.config.server.max_mau_value = 5
  89. self.get_success(self.store.reap_monthly_active_users())
  90. active_count = self.get_success(self.store.get_monthly_active_count())
  91. self.assertEqual(active_count, user_num)
  92. # Add some more users and check they are counted as active
  93. ru_count = 2
  94. self.get_success(self.store.upsert_monthly_active_user("@ru1:server"))
  95. self.get_success(self.store.upsert_monthly_active_user("@ru2:server"))
  96. active_count = self.get_success(self.store.get_monthly_active_count())
  97. self.assertEqual(active_count, user_num + ru_count)
  98. # now run the reaper and check that the number of active users is reduced
  99. # to max_mau_value
  100. self.get_success(self.store.reap_monthly_active_users())
  101. active_count = self.get_success(self.store.get_monthly_active_count())
  102. self.assertEqual(active_count, 3)
  103. def test_can_insert_and_count_mau(self):
  104. count = self.get_success(self.store.get_monthly_active_count())
  105. self.assertEqual(count, 0)
  106. d = self.store.upsert_monthly_active_user("@user:server")
  107. self.get_success(d)
  108. count = self.get_success(self.store.get_monthly_active_count())
  109. self.assertEqual(count, 1)
  110. def test_appservice_user_not_counted_in_mau(self):
  111. self.get_success(
  112. self.store.register_user(
  113. user_id="@appservice_user:server", appservice_id="wibble"
  114. )
  115. )
  116. count = self.get_success(self.store.get_monthly_active_count())
  117. self.assertEqual(count, 0)
  118. d = self.store.upsert_monthly_active_user("@appservice_user:server")
  119. self.get_success(d)
  120. count = self.get_success(self.store.get_monthly_active_count())
  121. self.assertEqual(count, 0)
  122. def test_user_last_seen_monthly_active(self):
  123. user_id1 = "@user1:server"
  124. user_id2 = "@user2:server"
  125. user_id3 = "@user3:server"
  126. result = self.get_success(self.store.user_last_seen_monthly_active(user_id1))
  127. self.assertNotEqual(result, 0)
  128. self.get_success(self.store.upsert_monthly_active_user(user_id1))
  129. self.get_success(self.store.upsert_monthly_active_user(user_id2))
  130. result = self.get_success(self.store.user_last_seen_monthly_active(user_id1))
  131. self.assertGreater(result, 0)
  132. result = self.get_success(self.store.user_last_seen_monthly_active(user_id3))
  133. self.assertNotEqual(result, 0)
  134. @override_config({"max_mau_value": 5})
  135. def test_reap_monthly_active_users(self):
  136. initial_users = 10
  137. for i in range(initial_users):
  138. self.get_success(
  139. self.store.upsert_monthly_active_user("@user%d:server" % i)
  140. )
  141. count = self.get_success(self.store.get_monthly_active_count())
  142. self.assertEqual(count, initial_users)
  143. d = self.store.reap_monthly_active_users()
  144. self.get_success(d)
  145. count = self.get_success(self.store.get_monthly_active_count())
  146. self.assertEqual(count, self.hs.config.server.max_mau_value)
  147. self.reactor.advance(FORTY_DAYS)
  148. d = self.store.reap_monthly_active_users()
  149. self.get_success(d)
  150. count = self.get_success(self.store.get_monthly_active_count())
  151. self.assertEqual(count, 0)
  152. # Note that below says mau_limit (no s), this is the name of the config
  153. # value, although it gets stored on the config object as mau_limits.
  154. @override_config({"max_mau_value": 5, "mau_limit_reserved_threepids": gen_3pids(5)})
  155. def test_reap_monthly_active_users_reserved_users(self):
  156. """Tests that reaping correctly handles reaping where reserved users are
  157. present"""
  158. threepids = self.hs.config.server.mau_limits_reserved_threepids
  159. initial_users = len(threepids)
  160. reserved_user_number = initial_users - 1
  161. for i in range(initial_users):
  162. user = "@user%d:server" % i
  163. email = "user%d@matrix.org" % i
  164. self.get_success(self.store.upsert_monthly_active_user(user))
  165. # Need to ensure that the most recent entries in the
  166. # monthly_active_users table are reserved
  167. now = int(self.hs.get_clock().time_msec())
  168. if i != 0:
  169. self.get_success(
  170. self.store.register_user(user_id=user, password_hash=None)
  171. )
  172. self.get_success(
  173. self.store.user_add_threepid(user, "email", email, now, now)
  174. )
  175. self.get_success(
  176. self.store.db_pool.runInteraction(
  177. "initialise", self.store._initialise_reserved_users, threepids
  178. )
  179. )
  180. count = self.get_success(self.store.get_monthly_active_count())
  181. self.assertEqual(count, initial_users)
  182. users = self.get_success(self.store.get_registered_reserved_users())
  183. self.assertEqual(len(users), reserved_user_number)
  184. self.get_success(self.store.reap_monthly_active_users())
  185. count = self.get_success(self.store.get_monthly_active_count())
  186. self.assertEqual(count, self.hs.config.server.max_mau_value)
  187. def test_populate_monthly_users_is_guest(self):
  188. # Test that guest users are not added to mau list
  189. user_id = "@user_id:host"
  190. d = self.store.register_user(
  191. user_id=user_id, password_hash=None, make_guest=True
  192. )
  193. self.get_success(d)
  194. self.store.upsert_monthly_active_user = Mock(return_value=make_awaitable(None)) # type: ignore[assignment]
  195. d = self.store.populate_monthly_active_users(user_id)
  196. self.get_success(d)
  197. self.store.upsert_monthly_active_user.assert_not_called()
  198. def test_populate_monthly_users_should_update(self):
  199. self.store.upsert_monthly_active_user = Mock(return_value=make_awaitable(None)) # type: ignore[assignment]
  200. self.store.is_trial_user = Mock(return_value=make_awaitable(False)) # type: ignore[assignment]
  201. self.store.user_last_seen_monthly_active = Mock(
  202. return_value=make_awaitable(None)
  203. )
  204. d = self.store.populate_monthly_active_users("user_id")
  205. self.get_success(d)
  206. self.store.upsert_monthly_active_user.assert_called_once()
  207. def test_populate_monthly_users_should_not_update(self):
  208. self.store.upsert_monthly_active_user = Mock(return_value=make_awaitable(None)) # type: ignore[assignment]
  209. self.store.is_trial_user = Mock(return_value=make_awaitable(False)) # type: ignore[assignment]
  210. self.store.user_last_seen_monthly_active = Mock(
  211. return_value=make_awaitable(self.hs.get_clock().time_msec())
  212. )
  213. d = self.store.populate_monthly_active_users("user_id")
  214. self.get_success(d)
  215. self.store.upsert_monthly_active_user.assert_not_called()
  216. def test_get_reserved_real_user_account(self):
  217. # Test no reserved users, or reserved threepids
  218. users = self.get_success(self.store.get_registered_reserved_users())
  219. self.assertEqual(len(users), 0)
  220. # Test reserved users but no registered users
  221. user1 = "@user1:example.com"
  222. user2 = "@user2:example.com"
  223. user1_email = "user1@example.com"
  224. user2_email = "user2@example.com"
  225. threepids = [
  226. {"medium": "email", "address": user1_email},
  227. {"medium": "email", "address": user2_email},
  228. ]
  229. self.hs.config.server.mau_limits_reserved_threepids = threepids
  230. d = self.store.db_pool.runInteraction(
  231. "initialise", self.store._initialise_reserved_users, threepids
  232. )
  233. self.get_success(d)
  234. users = self.get_success(self.store.get_registered_reserved_users())
  235. self.assertEqual(len(users), 0)
  236. # Test reserved registered users
  237. self.get_success(self.store.register_user(user_id=user1, password_hash=None))
  238. self.get_success(self.store.register_user(user_id=user2, password_hash=None))
  239. now = int(self.hs.get_clock().time_msec())
  240. self.get_success(
  241. self.store.user_add_threepid(user1, "email", user1_email, now, now)
  242. )
  243. self.get_success(
  244. self.store.user_add_threepid(user2, "email", user2_email, now, now)
  245. )
  246. users = self.get_success(self.store.get_registered_reserved_users())
  247. self.assertEqual(len(users), len(threepids))
  248. def test_support_user_not_add_to_mau_limits(self):
  249. support_user_id = "@support:test"
  250. count = self.get_success(self.store.get_monthly_active_count())
  251. self.assertEqual(count, 0)
  252. self.get_success(
  253. self.store.register_user(
  254. user_id=support_user_id, password_hash=None, user_type=UserTypes.SUPPORT
  255. )
  256. )
  257. self.get_success(self.store.upsert_monthly_active_user(support_user_id))
  258. count = self.get_success(self.store.get_monthly_active_count())
  259. self.assertEqual(count, 0)
  260. # Note that the max_mau_value setting should not matter.
  261. @override_config(
  262. {"limit_usage_by_mau": False, "mau_stats_only": True, "max_mau_value": 1}
  263. )
  264. def test_track_monthly_users_without_cap(self):
  265. count = self.get_success(self.store.get_monthly_active_count())
  266. self.assertEqual(0, count)
  267. self.get_success(self.store.upsert_monthly_active_user("@user1:server"))
  268. self.get_success(self.store.upsert_monthly_active_user("@user2:server"))
  269. count = self.get_success(self.store.get_monthly_active_count())
  270. self.assertEqual(2, count)
  271. @override_config({"limit_usage_by_mau": False, "mau_stats_only": False})
  272. def test_no_users_when_not_tracking(self):
  273. self.store.upsert_monthly_active_user = Mock(return_value=make_awaitable(None)) # type: ignore[assignment]
  274. self.get_success(self.store.populate_monthly_active_users("@user:sever"))
  275. self.store.upsert_monthly_active_user.assert_not_called()
  276. def test_get_monthly_active_count_by_service(self):
  277. appservice1_user1 = "@appservice1_user1:example.com"
  278. appservice1_user2 = "@appservice1_user2:example.com"
  279. appservice2_user1 = "@appservice2_user1:example.com"
  280. native_user1 = "@native_user1:example.com"
  281. service1 = "service1"
  282. service2 = "service2"
  283. native = "native"
  284. self.get_success(
  285. self.store.register_user(
  286. user_id=appservice1_user1, password_hash=None, appservice_id=service1
  287. )
  288. )
  289. self.get_success(
  290. self.store.register_user(
  291. user_id=appservice1_user2, password_hash=None, appservice_id=service1
  292. )
  293. )
  294. self.get_success(
  295. self.store.register_user(
  296. user_id=appservice2_user1, password_hash=None, appservice_id=service2
  297. )
  298. )
  299. self.get_success(
  300. self.store.register_user(user_id=native_user1, password_hash=None)
  301. )
  302. count1 = self.get_success(self.store.get_monthly_active_count_by_service())
  303. self.assertEqual(count1, {})
  304. self.get_success(self.store.upsert_monthly_active_user(native_user1))
  305. self.get_success(self.store.upsert_monthly_active_user(appservice1_user1))
  306. self.get_success(self.store.upsert_monthly_active_user(appservice1_user2))
  307. self.get_success(self.store.upsert_monthly_active_user(appservice2_user1))
  308. count2 = self.get_success(self.store.get_monthly_active_count())
  309. self.assertEqual(count2, 1)
  310. d = self.store.get_monthly_active_count_by_service()
  311. result = self.get_success(d)
  312. self.assertEqual(result[service1], 2)
  313. self.assertEqual(result[service2], 1)
  314. self.assertEqual(result[native], 1)
  315. def test_get_monthly_active_users_by_service(self):
  316. # (No users, no filtering) -> empty result
  317. result = self.get_success(self.store.get_monthly_active_users_by_service())
  318. self.assertEqual(len(result), 0)
  319. # (Some users, no filtering) -> non-empty result
  320. appservice1_user1 = "@appservice1_user1:example.com"
  321. appservice2_user1 = "@appservice2_user1:example.com"
  322. service1 = "service1"
  323. service2 = "service2"
  324. self.get_success(
  325. self.store.register_user(
  326. user_id=appservice1_user1, password_hash=None, appservice_id=service1
  327. )
  328. )
  329. self.get_success(self.store.upsert_monthly_active_user(appservice1_user1))
  330. self.get_success(
  331. self.store.register_user(
  332. user_id=appservice2_user1, password_hash=None, appservice_id=service2
  333. )
  334. )
  335. self.get_success(self.store.upsert_monthly_active_user(appservice2_user1))
  336. result = self.get_success(self.store.get_monthly_active_users_by_service())
  337. self.assertEqual(len(result), 2)
  338. self.assertIn((service1, appservice1_user1), result)
  339. self.assertIn((service2, appservice2_user1), result)
  340. # (Some users, end-timestamp filtering) -> non-empty result
  341. appservice1_user2 = "@appservice1_user2:example.com"
  342. timestamp1 = self.reactor.seconds()
  343. self.reactor.advance(5)
  344. timestamp2 = self.reactor.seconds()
  345. self.get_success(
  346. self.store.register_user(
  347. user_id=appservice1_user2, password_hash=None, appservice_id=service1
  348. )
  349. )
  350. self.get_success(self.store.upsert_monthly_active_user(appservice1_user2))
  351. result = self.get_success(
  352. self.store.get_monthly_active_users_by_service(
  353. end_timestamp=round(timestamp1 * 1000)
  354. )
  355. )
  356. self.assertEqual(len(result), 2)
  357. self.assertNotIn((service1, appservice1_user2), result)
  358. # (Some users, start-timestamp filtering) -> non-empty result
  359. result = self.get_success(
  360. self.store.get_monthly_active_users_by_service(
  361. start_timestamp=round(timestamp2 * 1000)
  362. )
  363. )
  364. self.assertEqual(len(result), 1)
  365. self.assertIn((service1, appservice1_user2), result)
  366. # (Some users, full-timestamp filtering) -> non-empty result
  367. native_user1 = "@native_user1:example.com"
  368. native = "native"
  369. timestamp3 = self.reactor.seconds()
  370. self.reactor.advance(100)
  371. self.get_success(
  372. self.store.register_user(
  373. user_id=native_user1, password_hash=None, appservice_id=native
  374. )
  375. )
  376. self.get_success(self.store.upsert_monthly_active_user(native_user1))
  377. result = self.get_success(
  378. self.store.get_monthly_active_users_by_service(
  379. start_timestamp=round(timestamp2 * 1000),
  380. end_timestamp=round(timestamp3 * 1000),
  381. )
  382. )
  383. self.assertEqual(len(result), 1)
  384. self.assertIn((service1, appservice1_user2), result)