client_ips.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 Vector Creations 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.storage.database import DatabasePool
  16. from synapse.storage.databases.main.client_ips import LAST_SEEN_GRANULARITY
  17. from synapse.util.caches.descriptors import Cache
  18. from ._base import BaseSlavedStore
  19. class SlavedClientIpStore(BaseSlavedStore):
  20. def __init__(self, database: DatabasePool, db_conn, hs):
  21. super(SlavedClientIpStore, self).__init__(database, db_conn, hs)
  22. self.client_ip_last_seen = Cache(
  23. name="client_ip_last_seen", keylen=4, max_entries=50000
  24. )
  25. def insert_client_ip(self, user_id, access_token, ip, user_agent, device_id):
  26. now = int(self._clock.time_msec())
  27. key = (user_id, access_token, ip)
  28. try:
  29. last_seen = self.client_ip_last_seen.get(key)
  30. except KeyError:
  31. last_seen = None
  32. # Rate-limited inserts
  33. if last_seen is not None and (now - last_seen) < LAST_SEEN_GRANULARITY:
  34. return
  35. self.client_ip_last_seen.prefill(key, now)
  36. self.hs.get_tcp_replication().send_user_ip(
  37. user_id, access_token, ip, user_agent, device_id, now
  38. )