2018-08-03 06:49:53 -06:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# Copyright 2018 New Vector
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2018-08-07 10:49:43 -06:00
|
|
|
import logging
|
2018-08-03 06:49:53 -06:00
|
|
|
|
2018-07-31 09:36:24 -06:00
|
|
|
from twisted.internet import defer
|
2018-08-03 06:49:53 -06:00
|
|
|
|
2018-08-06 10:51:15 -06:00
|
|
|
from synapse.util.caches.descriptors import cached
|
2018-07-31 09:36:24 -06:00
|
|
|
|
|
|
|
from ._base import SQLBaseStore
|
|
|
|
|
2018-08-07 10:49:43 -06:00
|
|
|
logger = logging.getLogger(__name__)
|
2018-08-06 16:25:25 -06:00
|
|
|
|
2018-08-03 10:55:50 -06:00
|
|
|
# Number of msec of granularity to store the monthly_active_user timestamp
|
|
|
|
# This means it is not necessary to update the table on every request
|
|
|
|
LAST_SEEN_GRANULARITY = 60 * 60 * 1000
|
|
|
|
|
2018-07-31 09:36:24 -06:00
|
|
|
|
|
|
|
class MonthlyActiveUsersStore(SQLBaseStore):
|
2018-08-02 06:47:19 -06:00
|
|
|
def __init__(self, dbconn, hs):
|
2018-07-31 09:36:24 -06:00
|
|
|
super(MonthlyActiveUsersStore, self).__init__(None, hs)
|
|
|
|
self._clock = hs.get_clock()
|
2018-08-03 06:49:53 -06:00
|
|
|
self.hs = hs
|
2018-08-07 10:49:43 -06:00
|
|
|
self.reserved_users = ()
|
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
|
|
|
def initialise_reserved_users(self, threepids):
|
|
|
|
store = self.hs.get_datastore()
|
|
|
|
reserved_user_list = []
|
2018-08-07 10:59:27 -06:00
|
|
|
|
|
|
|
# Do not add more reserved users than the total allowable number
|
|
|
|
for tp in threepids[:self.hs.config.max_mau_value]:
|
2018-08-07 10:49:43 -06:00
|
|
|
user_id = yield store.get_user_id_by_threepid(
|
2018-08-06 16:25:25 -06:00
|
|
|
tp["medium"], tp["address"]
|
|
|
|
)
|
|
|
|
if user_id:
|
2018-08-14 09:55:28 -06:00
|
|
|
yield self.upsert_monthly_active_user(user_id)
|
2018-08-07 10:49:43 -06:00
|
|
|
reserved_user_list.append(user_id)
|
2018-08-06 16:25:25 -06:00
|
|
|
else:
|
|
|
|
logger.warning(
|
|
|
|
"mau limit reserved threepid %s not found in db" % tp
|
|
|
|
)
|
2018-08-07 10:49:43 -06:00
|
|
|
self.reserved_users = tuple(reserved_user_list)
|
2018-07-31 09:36:24 -06:00
|
|
|
|
2018-08-07 10:49:43 -06:00
|
|
|
@defer.inlineCallbacks
|
2018-07-31 09:36:24 -06:00
|
|
|
def reap_monthly_active_users(self):
|
|
|
|
"""
|
|
|
|
Cleans out monthly active user table to ensure that no stale
|
|
|
|
entries exist.
|
2018-08-03 10:55:50 -06:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
Deferred[]
|
2018-07-31 09:36:24 -06:00
|
|
|
"""
|
|
|
|
def _reap_users(txn):
|
2018-08-11 15:38:34 -06:00
|
|
|
# Purge stale users
|
2018-08-03 06:49:53 -06:00
|
|
|
|
2018-07-31 09:36:24 -06:00
|
|
|
thirty_days_ago = (
|
|
|
|
int(self._clock.time_msec()) - (1000 * 60 * 60 * 24 * 30)
|
|
|
|
)
|
2018-08-07 10:49:43 -06:00
|
|
|
query_args = [thirty_days_ago]
|
2018-08-11 15:38:34 -06:00
|
|
|
base_sql = "DELETE FROM monthly_active_users WHERE timestamp < ?"
|
|
|
|
|
|
|
|
# Need if/else since 'AND user_id NOT IN ({})' fails on Postgres
|
|
|
|
# when len(reserved_users) == 0. Works fine on sqlite.
|
|
|
|
if len(self.reserved_users) > 0:
|
|
|
|
# questionmarks is a hack to overcome sqlite not supporting
|
|
|
|
# tuples in 'WHERE IN %s'
|
|
|
|
questionmarks = '?' * len(self.reserved_users)
|
|
|
|
|
|
|
|
query_args.extend(self.reserved_users)
|
|
|
|
sql = base_sql + """ AND user_id NOT IN ({})""".format(
|
|
|
|
','.join(questionmarks)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
sql = base_sql
|
2018-08-07 10:49:43 -06:00
|
|
|
|
|
|
|
txn.execute(sql, query_args)
|
2018-08-06 14:55:54 -06:00
|
|
|
|
|
|
|
# If MAU user count still exceeds the MAU threshold, then delete on
|
|
|
|
# a least recently active basis.
|
|
|
|
# Note it is not possible to write this query using OFFSET due to
|
2018-08-08 06:33:16 -06:00
|
|
|
# incompatibilities in how sqlite and postgres support the feature.
|
2018-08-06 14:55:54 -06:00
|
|
|
# sqlite requires 'LIMIT -1 OFFSET ?', the LIMIT must be present
|
|
|
|
# While Postgres does not require 'LIMIT', but also does not support
|
|
|
|
# negative LIMIT values. So there is no way to write it that both can
|
|
|
|
# support
|
2018-08-16 15:55:32 -06:00
|
|
|
safe_guard = self.hs.config.max_mau_value - len(self.reserved_users)
|
|
|
|
# Must be greater than zero for postgres
|
|
|
|
safe_guard = safe_guard if safe_guard > 0 else 0
|
|
|
|
query_args = [safe_guard]
|
2018-08-11 15:38:34 -06:00
|
|
|
|
|
|
|
base_sql = """
|
2018-08-03 06:49:53 -06:00
|
|
|
DELETE FROM monthly_active_users
|
2018-08-06 14:55:54 -06:00
|
|
|
WHERE user_id NOT IN (
|
|
|
|
SELECT user_id FROM monthly_active_users
|
|
|
|
ORDER BY timestamp DESC
|
|
|
|
LIMIT ?
|
|
|
|
)
|
2018-08-11 15:38:34 -06:00
|
|
|
"""
|
|
|
|
# Need if/else since 'AND user_id NOT IN ({})' fails on Postgres
|
|
|
|
# when len(reserved_users) == 0. Works fine on sqlite.
|
|
|
|
if len(self.reserved_users) > 0:
|
|
|
|
query_args.extend(self.reserved_users)
|
|
|
|
sql = base_sql + """ AND user_id NOT IN ({})""".format(
|
|
|
|
','.join(questionmarks)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
sql = base_sql
|
2018-08-07 10:49:43 -06:00
|
|
|
txn.execute(sql, query_args)
|
2018-08-02 15:41:05 -06:00
|
|
|
|
2018-08-03 15:29:03 -06:00
|
|
|
yield self.runInteraction("reap_monthly_active_users", _reap_users)
|
2018-08-03 06:49:53 -06:00
|
|
|
# It seems poor to invalidate the whole cache, Postgres supports
|
|
|
|
# 'Returning' which would allow me to invalidate only the
|
|
|
|
# specific users, but sqlite has no way to do this and instead
|
|
|
|
# I would need to SELECT and the DELETE which without locking
|
|
|
|
# is racy.
|
|
|
|
# Have resolved to invalidate the whole cache for now and do
|
|
|
|
# something about it if and when the perf becomes significant
|
2018-08-09 11:02:12 -06:00
|
|
|
self.user_last_seen_monthly_active.invalidate_all()
|
2018-08-03 06:49:53 -06:00
|
|
|
self.get_monthly_active_count.invalidate_all()
|
2018-08-02 15:41:05 -06:00
|
|
|
|
2018-08-03 06:49:53 -06:00
|
|
|
@cached(num_args=0)
|
2018-07-31 09:36:24 -06:00
|
|
|
def get_monthly_active_count(self):
|
2018-08-06 16:25:25 -06:00
|
|
|
"""Generates current count of monthly active users
|
2018-08-03 10:55:50 -06:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
Defered[int]: Number of current monthly active users
|
2018-07-31 09:36:24 -06:00
|
|
|
"""
|
2018-08-03 06:49:53 -06:00
|
|
|
|
2018-07-31 09:36:24 -06:00
|
|
|
def _count_users(txn):
|
2018-08-01 05:03:57 -06:00
|
|
|
sql = "SELECT COALESCE(count(*), 0) FROM monthly_active_users"
|
|
|
|
|
2018-07-31 09:36:24 -06:00
|
|
|
txn.execute(sql)
|
|
|
|
count, = txn.fetchone()
|
|
|
|
return count
|
|
|
|
return self.runInteraction("count_users", _count_users)
|
|
|
|
|
2018-09-12 04:58:52 -06:00
|
|
|
@defer.inlineCallbacks
|
2018-09-12 09:22:15 -06:00
|
|
|
def get_registered_reserved_users_count(self):
|
2018-09-12 04:58:52 -06:00
|
|
|
"""Of the reserved threepids defined in config, how many are associated
|
|
|
|
with registered users?
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Defered[int]: Number of real reserved users
|
|
|
|
"""
|
|
|
|
count = 0
|
|
|
|
for tp in self.hs.config.mau_limits_reserved_threepids:
|
|
|
|
user_id = yield self.hs.get_datastore().get_user_id_by_threepid(
|
|
|
|
tp["medium"], tp["address"]
|
|
|
|
)
|
|
|
|
if user_id:
|
|
|
|
count = count + 1
|
|
|
|
defer.returnValue(count)
|
|
|
|
|
2018-08-23 03:28:10 -06:00
|
|
|
@defer.inlineCallbacks
|
2018-08-02 03:59:58 -06:00
|
|
|
def upsert_monthly_active_user(self, user_id):
|
2018-07-31 09:36:24 -06:00
|
|
|
"""
|
|
|
|
Updates or inserts monthly active user member
|
|
|
|
Arguments:
|
|
|
|
user_id (str): user to add/update
|
2018-08-03 10:55:50 -06:00
|
|
|
Deferred[bool]: True if a new entry was created, False if an
|
2018-08-02 06:47:19 -06:00
|
|
|
existing one was updated.
|
2018-07-31 09:36:24 -06:00
|
|
|
"""
|
2018-09-26 09:16:41 -06:00
|
|
|
# Am consciously deciding to lock the table on the basis that is ought
|
|
|
|
# never be a big table and alternative approaches (batching multiple
|
|
|
|
# upserts into a single txn) introduced a lot of extra complexity.
|
|
|
|
# See https://github.com/matrix-org/synapse/issues/3854 for more
|
2018-08-23 03:28:10 -06:00
|
|
|
is_insert = yield self._simple_upsert(
|
2018-07-31 09:36:24 -06:00
|
|
|
desc="upsert_monthly_active_user",
|
|
|
|
table="monthly_active_users",
|
2018-08-02 03:59:58 -06:00
|
|
|
keyvalues={
|
2018-08-01 10:54:37 -06:00
|
|
|
"user_id": user_id,
|
2018-07-31 09:36:24 -06:00
|
|
|
},
|
2018-08-02 03:59:58 -06:00
|
|
|
values={
|
|
|
|
"timestamp": int(self._clock.time_msec()),
|
|
|
|
},
|
2018-07-31 09:36:24 -06:00
|
|
|
)
|
2018-08-03 10:55:50 -06:00
|
|
|
if is_insert:
|
2018-08-09 11:02:12 -06:00
|
|
|
self.user_last_seen_monthly_active.invalidate((user_id,))
|
2018-08-03 10:55:50 -06:00
|
|
|
self.get_monthly_active_count.invalidate(())
|
2018-07-31 09:36:24 -06:00
|
|
|
|
2018-08-06 10:51:15 -06:00
|
|
|
@cached(num_args=1)
|
2018-08-09 11:02:12 -06:00
|
|
|
def user_last_seen_monthly_active(self, user_id):
|
2018-07-31 09:36:24 -06:00
|
|
|
"""
|
|
|
|
Checks if a given user is part of the monthly active user group
|
|
|
|
Arguments:
|
|
|
|
user_id (str): user to add/update
|
|
|
|
Return:
|
2018-08-07 10:49:43 -06:00
|
|
|
Deferred[int] : timestamp since last seen, None if never seen
|
2018-08-03 10:55:50 -06:00
|
|
|
|
2018-07-31 09:36:24 -06:00
|
|
|
"""
|
2018-08-06 10:51:15 -06:00
|
|
|
|
|
|
|
return(self._simple_select_one_onecol(
|
2018-07-31 09:36:24 -06:00
|
|
|
table="monthly_active_users",
|
|
|
|
keyvalues={
|
|
|
|
"user_id": user_id,
|
|
|
|
},
|
2018-08-03 10:55:50 -06:00
|
|
|
retcol="timestamp",
|
2018-08-06 10:51:15 -06:00
|
|
|
allow_none=True,
|
2018-08-09 11:02:12 -06:00
|
|
|
desc="user_last_seen_monthly_active",
|
2018-08-06 10:51:15 -06:00
|
|
|
))
|
2018-08-03 10:55:50 -06:00
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
2018-09-06 10:22:53 -06:00
|
|
|
def populate_monthly_active_users(self, user_id):
|
2018-08-03 10:55:50 -06:00
|
|
|
"""Checks on the state of monthly active user limits and optionally
|
|
|
|
add the user to the monthly active tables
|
|
|
|
|
|
|
|
Args:
|
|
|
|
user_id(str): the user_id to query
|
|
|
|
"""
|
2018-09-05 15:30:36 -06:00
|
|
|
|
2018-08-03 10:55:50 -06:00
|
|
|
if self.hs.config.limit_usage_by_mau:
|
2018-09-06 10:22:53 -06:00
|
|
|
# Trial users and guests should not be included as part of MAU group
|
|
|
|
is_guest = yield self.is_guest(user_id)
|
2018-09-05 15:30:36 -06:00
|
|
|
if is_guest:
|
|
|
|
return
|
2018-08-23 12:17:08 -06:00
|
|
|
is_trial = yield self.is_trial_user(user_id)
|
|
|
|
if is_trial:
|
|
|
|
return
|
|
|
|
|
2018-08-09 11:02:12 -06:00
|
|
|
last_seen_timestamp = yield self.user_last_seen_monthly_active(user_id)
|
2018-08-03 10:55:50 -06:00
|
|
|
now = self.hs.get_clock().time_msec()
|
|
|
|
|
2018-08-06 10:51:15 -06:00
|
|
|
# We want to reduce to the total number of db writes, and are happy
|
|
|
|
# to trade accuracy of timestamp in order to lighten load. This means
|
|
|
|
# We always insert new users (where MAU threshold has not been reached),
|
|
|
|
# but only update if we have not previously seen the user for
|
|
|
|
# LAST_SEEN_GRANULARITY ms
|
2018-08-03 10:55:50 -06:00
|
|
|
if last_seen_timestamp is None:
|
|
|
|
count = yield self.get_monthly_active_count()
|
|
|
|
if count < self.hs.config.max_mau_value:
|
|
|
|
yield self.upsert_monthly_active_user(user_id)
|
|
|
|
elif now - last_seen_timestamp > LAST_SEEN_GRANULARITY:
|
|
|
|
yield self.upsert_monthly_active_user(user_id)
|