class SlavedClientIpStore(BaseSlavedStore): def __init__(self, database: DatabasePool, db_conn, hs): super().__init__(database, db_conn, hs) self.client_ip_last_seen = LruCache( cache_name="client_ip_last_seen", keylen=4, max_size=50000) # type: LruCache[tuple, int] async def insert_client_ip(self, user_id, access_token, ip, user_agent, device_id): now = int(self._clock.time_msec()) key = (user_id, access_token, ip) try: last_seen = self.client_ip_last_seen.get(key) except KeyError: last_seen = None # Rate-limited inserts if last_seen is not None and (now - last_seen) < LAST_SEEN_GRANULARITY: return self.client_ip_last_seen.set(key, now) self.hs.get_tcp_replication().send_user_ip(user_id, access_token, ip, user_agent, device_id, now)
def test_clear(self): m1 = Mock() m2 = Mock() cache = LruCache(5) cache.set("key1", "value", callbacks=[m1]) cache.set("key2", "value", callbacks=[m2]) self.assertEquals(m1.call_count, 0) self.assertEquals(m2.call_count, 0) cache.clear() self.assertEquals(m1.call_count, 1) self.assertEquals(m2.call_count, 1)
def test_pop(self): m = Mock() cache = LruCache(1) cache.set("key", "value", callbacks=[m]) self.assertFalse(m.called) cache.pop("key") self.assertEquals(m.call_count, 1) cache.set("key", "value") self.assertEquals(m.call_count, 1) cache.pop("key") self.assertEquals(m.call_count, 1)
def test_set(self): m = Mock() cache = LruCache(1) cache.set("key", "value", m) self.assertFalse(m.called) cache.set("key", "value") self.assertFalse(m.called) cache.set("key", "value2") self.assertEquals(m.call_count, 1) cache.set("key", "value") self.assertEquals(m.call_count, 1)
def test_del_multi(self): m1 = Mock() m2 = Mock() m3 = Mock() m4 = Mock() cache = LruCache(4, 2, cache_type=TreeCache) cache.set(("a", "1"), "value", callbacks=[m1]) cache.set(("a", "2"), "value", callbacks=[m2]) cache.set(("b", "1"), "value", callbacks=[m3]) cache.set(("b", "2"), "value", callbacks=[m4]) self.assertEquals(m1.call_count, 0) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 0) self.assertEquals(m4.call_count, 0) cache.del_multi(("a",)) self.assertEquals(m1.call_count, 1) self.assertEquals(m2.call_count, 1) self.assertEquals(m3.call_count, 0) self.assertEquals(m4.call_count, 0)
def test_eviction(self): m1 = Mock(name="m1") m2 = Mock(name="m2") m3 = Mock(name="m3") cache = LruCache(2) cache.set("key1", "value", callbacks=[m1]) cache.set("key2", "value", callbacks=[m2]) self.assertEquals(m1.call_count, 0) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 0) cache.set("key3", "value", callbacks=[m3]) self.assertEquals(m1.call_count, 1) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 0) cache.set("key3", "value") self.assertEquals(m1.call_count, 1) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 0) cache.get("key2") self.assertEquals(m1.call_count, 1) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 0) cache.set("key1", "value", callbacks=[m1]) self.assertEquals(m1.call_count, 1) self.assertEquals(m2.call_count, 0) self.assertEquals(m3.call_count, 1)
def test_multi_get(self): m = Mock() cache = LruCache(1) cache.set("key", "value") self.assertFalse(m.called) cache.get("key", callbacks=[m]) self.assertFalse(m.called) cache.get("key", callbacks=[m]) self.assertFalse(m.called) cache.set("key", "value2") self.assertEqual(m.call_count, 1) cache.set("key", "value") self.assertEqual(m.call_count, 1)
class EventFederationWorkerStore(EventsWorkerStore, SignatureWorkerStore, SQLBaseStore): def __init__(self, database: DatabasePool, db_conn, hs): super().__init__(database, db_conn, hs) if hs.config.run_background_tasks: hs.get_clock().looping_call(self._delete_old_forward_extrem_cache, 60 * 60 * 1000) # Cache of event ID to list of auth event IDs and their depths. self._event_auth_cache = LruCache( 500000, "_event_auth_cache", size_callback=len) # type: LruCache[str, List[Tuple[str, int]]] async def get_auth_chain(self, event_ids: Collection[str], include_given: bool = False) -> List[EventBase]: """Get auth events for given event_ids. The events *must* be state events. Args: event_ids: state events include_given: include the given events in result Returns: list of events """ event_ids = await self.get_auth_chain_ids(event_ids, include_given=include_given) return await self.get_events_as_list(event_ids) async def get_auth_chain_ids( self, event_ids: Collection[str], include_given: bool = False, ) -> List[str]: """Get auth events for given event_ids. The events *must* be state events. Args: event_ids: state events include_given: include the given events in result Returns: An awaitable which resolve to a list of event_ids """ return await self.db_pool.runInteraction( "get_auth_chain_ids", self._get_auth_chain_ids_txn, event_ids, include_given, ) def _get_auth_chain_ids_txn(self, txn: LoggingTransaction, event_ids: Collection[str], include_given: bool) -> List[str]: if include_given: results = set(event_ids) else: results = set() # We pull out the depth simply so that we can populate the # `_event_auth_cache` cache. base_sql = """ SELECT a.event_id, auth_id, depth FROM event_auth AS a INNER JOIN events AS e ON (e.event_id = a.auth_id) WHERE """ front = set(event_ids) while front: new_front = set() for chunk in batch_iter(front, 100): # Pull the auth events either from the cache or DB. to_fetch = [] # Event IDs to fetch from DB # type: List[str] for event_id in chunk: res = self._event_auth_cache.get(event_id) if res is None: to_fetch.append(event_id) else: new_front.update(auth_id for auth_id, depth in res) if to_fetch: clause, args = make_in_list_sql_clause( txn.database_engine, "a.event_id", to_fetch) txn.execute(base_sql + clause, args) # Note we need to batch up the results by event ID before # adding to the cache. to_cache = {} for event_id, auth_event_id, auth_event_depth in txn: to_cache.setdefault(event_id, []).append( (auth_event_id, auth_event_depth)) new_front.add(auth_event_id) for event_id, auth_events in to_cache.items(): self._event_auth_cache.set(event_id, auth_events) new_front -= results front = new_front results.update(front) return list(results) async def get_auth_chain_difference( self, room_id: str, state_sets: List[Set[str]]) -> Set[str]: """Given sets of state events figure out the auth chain difference (as per state res v2 algorithm). This equivalent to fetching the full auth chain for each set of state and returning the events that don't appear in each and every auth chain. Returns: The set of the difference in auth chains. """ return await self.db_pool.runInteraction( "get_auth_chain_difference", self._get_auth_chain_difference_txn, state_sets, ) def _get_auth_chain_difference_txn(self, txn, state_sets: List[Set[str]]) -> Set[str]: # Algorithm Description # ~~~~~~~~~~~~~~~~~~~~~ # # The idea here is to basically walk the auth graph of each state set in # tandem, keeping track of which auth events are reachable by each state # set. If we reach an auth event we've already visited (via a different # state set) then we mark that auth event and all ancestors as reachable # by the state set. This requires that we keep track of the auth chains # in memory. # # Doing it in a such a way means that we can stop early if all auth # events we're currently walking are reachable by all state sets. # # *Note*: We can't stop walking an event's auth chain if it is reachable # by all state sets. This is because other auth chains we're walking # might be reachable only via the original auth chain. For example, # given the following auth chain: # # A -> C -> D -> E # / / # B -´---------´ # # and state sets {A} and {B} then walking the auth chains of A and B # would immediately show that C is reachable by both. However, if we # stopped at C then we'd only reach E via the auth chain of B and so E # would errornously get included in the returned difference. # # The other thing that we do is limit the number of auth chains we walk # at once, due to practical limits (i.e. we can only query the database # with a limited set of parameters). We pick the auth chains we walk # each iteration based on their depth, in the hope that events with a # lower depth are likely reachable by those with higher depths. # # We could use any ordering that we believe would give a rough # topological ordering, e.g. origin server timestamp. If the ordering # chosen is not topological then the algorithm still produces the right # result, but perhaps a bit more inefficiently. This is why it is safe # to use "depth" here. initial_events = set(state_sets[0]).union(*state_sets[1:]) # Dict from events in auth chains to which sets *cannot* reach them. # I.e. if the set is empty then all sets can reach the event. event_to_missing_sets = { event_id: {i for i, a in enumerate(state_sets) if event_id not in a} for event_id in initial_events } # The sorted list of events whose auth chains we should walk. search = [] # type: List[Tuple[int, str]] # We need to get the depth of the initial events for sorting purposes. sql = """ SELECT depth, event_id FROM events WHERE %s """ # the list can be huge, so let's avoid looking them all up in one massive # query. for batch in batch_iter(initial_events, 1000): clause, args = make_in_list_sql_clause(txn.database_engine, "event_id", batch) txn.execute(sql % (clause, ), args) # I think building a temporary list with fetchall is more efficient than # just `search.extend(txn)`, but this is unconfirmed search.extend(txn.fetchall()) # sort by depth search.sort() # Map from event to its auth events event_to_auth_events = {} # type: Dict[str, Set[str]] base_sql = """ SELECT a.event_id, auth_id, depth FROM event_auth AS a INNER JOIN events AS e ON (e.event_id = a.auth_id) WHERE """ while search: # Check whether all our current walks are reachable by all state # sets. If so we can bail. if all(not event_to_missing_sets[eid] for _, eid in search): break # Fetch the auth events and their depths of the N last events we're # currently walking, either from cache or DB. search, chunk = search[:-100], search[-100:] found = [] # Results found # type: List[Tuple[str, str, int]] to_fetch = [] # Event IDs to fetch from DB # type: List[str] for _, event_id in chunk: res = self._event_auth_cache.get(event_id) if res is None: to_fetch.append(event_id) else: found.extend( (event_id, auth_id, depth) for auth_id, depth in res) if to_fetch: clause, args = make_in_list_sql_clause(txn.database_engine, "a.event_id", to_fetch) txn.execute(base_sql + clause, args) # We parse the results and add the to the `found` set and the # cache (note we need to batch up the results by event ID before # adding to the cache). to_cache = {} for event_id, auth_event_id, auth_event_depth in txn: to_cache.setdefault(event_id, []).append( (auth_event_id, auth_event_depth)) found.append((event_id, auth_event_id, auth_event_depth)) for event_id, auth_events in to_cache.items(): self._event_auth_cache.set(event_id, auth_events) for event_id, auth_event_id, auth_event_depth in found: event_to_auth_events.setdefault(event_id, set()).add(auth_event_id) sets = event_to_missing_sets.get(auth_event_id) if sets is None: # First time we're seeing this event, so we add it to the # queue of things to fetch. search.append((auth_event_depth, auth_event_id)) # Assume that this event is unreachable from any of the # state sets until proven otherwise sets = event_to_missing_sets[auth_event_id] = set( range(len(state_sets))) else: # We've previously seen this event, so look up its auth # events and recursively mark all ancestors as reachable # by the current event's state set. a_ids = event_to_auth_events.get(auth_event_id) while a_ids: new_aids = set() for a_id in a_ids: event_to_missing_sets[a_id].intersection_update( event_to_missing_sets[event_id]) b = event_to_auth_events.get(a_id) if b: new_aids.update(b) a_ids = new_aids # Mark that the auth event is reachable by the approriate sets. sets.intersection_update(event_to_missing_sets[event_id]) search.sort() # Return all events where not all sets can reach them. return {eid for eid, n in event_to_missing_sets.items() if n} async def get_oldest_events_with_depth_in_room(self, room_id): return await self.db_pool.runInteraction( "get_oldest_events_with_depth_in_room", self.get_oldest_events_with_depth_in_room_txn, room_id, ) def get_oldest_events_with_depth_in_room_txn(self, txn, room_id): sql = ("SELECT b.event_id, MAX(e.depth) FROM events as e" " INNER JOIN event_edges as g" " ON g.event_id = e.event_id" " INNER JOIN event_backward_extremities as b" " ON g.prev_event_id = b.event_id" " WHERE b.room_id = ? AND g.is_state is ?" " GROUP BY b.event_id") txn.execute(sql, (room_id, False)) return dict(txn) async def get_max_depth_of(self, event_ids: List[str]) -> int: """Returns the max depth of a set of event IDs Args: event_ids: The event IDs to calculate the max depth of. """ rows = await self.db_pool.simple_select_many_batch( table="events", column="event_id", iterable=event_ids, retcols=("depth", ), desc="get_max_depth_of", ) if not rows: return 0 else: return max(row["depth"] for row in rows) async def get_prev_events_for_room(self, room_id: str) -> List[str]: """ Gets a subset of the current forward extremities in the given room. Limits the result to 10 extremities, so that we can avoid creating events which refer to hundreds of prev_events. Args: room_id: room_id Returns: The event ids of the forward extremities. """ return await self.db_pool.runInteraction( "get_prev_events_for_room", self._get_prev_events_for_room_txn, room_id) def _get_prev_events_for_room_txn(self, txn, room_id: str): # we just use the 10 newest events. Older events will become # prev_events of future events. sql = """ SELECT e.event_id FROM event_forward_extremities AS f INNER JOIN events AS e USING (event_id) WHERE f.room_id = ? ORDER BY e.depth DESC LIMIT 10 """ txn.execute(sql, (room_id, )) return [row[0] for row in txn] async def get_rooms_with_many_extremities( self, min_count: int, limit: int, room_id_filter: Iterable[str]) -> List[str]: """Get the top rooms with at least N extremities. Args: min_count: The minimum number of extremities limit: The maximum number of rooms to return. room_id_filter: room_ids to exclude from the results Returns: At most `limit` room IDs that have at least `min_count` extremities, sorted by extremity count. """ def _get_rooms_with_many_extremities_txn(txn): where_clause = "1=1" if room_id_filter: where_clause = "room_id NOT IN (%s)" % (",".join( "?" for _ in room_id_filter), ) sql = """ SELECT room_id FROM event_forward_extremities WHERE %s GROUP BY room_id HAVING count(*) > ? ORDER BY count(*) DESC LIMIT ? """ % (where_clause, ) query_args = list( itertools.chain(room_id_filter, [min_count, limit])) txn.execute(sql, query_args) return [room_id for room_id, in txn] return await self.db_pool.runInteraction( "get_rooms_with_many_extremities", _get_rooms_with_many_extremities_txn) @cached(max_entries=5000, iterable=True) async def get_latest_event_ids_in_room(self, room_id: str) -> List[str]: return await self.db_pool.simple_select_onecol( table="event_forward_extremities", keyvalues={"room_id": room_id}, retcol="event_id", desc="get_latest_event_ids_in_room", ) async def get_min_depth(self, room_id: str) -> int: """For the given room, get the minimum depth we have seen for it. """ return await self.db_pool.runInteraction( "get_min_depth", self._get_min_depth_interaction, room_id) def _get_min_depth_interaction(self, txn, room_id): min_depth = self.db_pool.simple_select_one_onecol_txn( txn, table="room_depth", keyvalues={"room_id": room_id}, retcol="min_depth", allow_none=True, ) return int(min_depth) if min_depth is not None else None async def get_forward_extremeties_for_room( self, room_id: str, stream_ordering: int) -> List[str]: """For a given room_id and stream_ordering, return the forward extremeties of the room at that point in "time". Throws a StoreError if we have since purged the index for stream_orderings from that point. Args: room_id: stream_ordering: Returns: A list of event_ids """ # We want to make the cache more effective, so we clamp to the last # change before the given ordering. last_change = self._events_stream_cache.get_max_pos_of_last_change( room_id) # We don't always have a full stream_to_exterm_id table, e.g. after # the upgrade that introduced it, so we make sure we never ask for a # stream_ordering from before a restart last_change = max(self._stream_order_on_start, last_change) # provided the last_change is recent enough, we now clamp the requested # stream_ordering to it. if last_change > self.stream_ordering_month_ago: stream_ordering = min(last_change, stream_ordering) return await self._get_forward_extremeties_for_room( room_id, stream_ordering) @cached(max_entries=5000, num_args=2) async def _get_forward_extremeties_for_room(self, room_id, stream_ordering): """For a given room_id and stream_ordering, return the forward extremeties of the room at that point in "time". Throws a StoreError if we have since purged the index for stream_orderings from that point. """ if stream_ordering <= self.stream_ordering_month_ago: raise StoreError( 400, "stream_ordering too old %s" % (stream_ordering, )) sql = """ SELECT event_id FROM stream_ordering_to_exterm INNER JOIN ( SELECT room_id, MAX(stream_ordering) AS stream_ordering FROM stream_ordering_to_exterm WHERE stream_ordering <= ? GROUP BY room_id ) AS rms USING (room_id, stream_ordering) WHERE room_id = ? """ def get_forward_extremeties_for_room_txn(txn): txn.execute(sql, (stream_ordering, room_id)) return [event_id for event_id, in txn] return await self.db_pool.runInteraction( "get_forward_extremeties_for_room", get_forward_extremeties_for_room_txn) async def get_backfill_events(self, room_id: str, event_list: list, limit: int): """Get a list of Events for a given topic that occurred before (and including) the events in event_list. Return a list of max size `limit` Args: room_id event_list limit """ event_ids = await self.db_pool.runInteraction( "get_backfill_events", self._get_backfill_events, room_id, event_list, limit, ) events = await self.get_events_as_list(event_ids) return sorted(events, key=lambda e: -e.depth) def _get_backfill_events(self, txn, room_id, event_list, limit): logger.debug("_get_backfill_events: %s, %r, %s", room_id, event_list, limit) event_results = set() # We want to make sure that we do a breadth-first, "depth" ordered # search. query = ("SELECT depth, prev_event_id FROM event_edges" " INNER JOIN events" " ON prev_event_id = events.event_id" " WHERE event_edges.event_id = ?" " AND event_edges.is_state = ?" " LIMIT ?") queue = PriorityQueue() for event_id in event_list: depth = self.db_pool.simple_select_one_onecol_txn( txn, table="events", keyvalues={ "event_id": event_id, "room_id": room_id }, retcol="depth", allow_none=True, ) if depth: queue.put((-depth, event_id)) while not queue.empty() and len(event_results) < limit: try: _, event_id = queue.get_nowait() except Empty: break if event_id in event_results: continue event_results.add(event_id) txn.execute(query, (event_id, False, limit - len(event_results))) for row in txn: if row[1] not in event_results: queue.put((-row[0], row[1])) return event_results async def get_missing_events(self, room_id, earliest_events, latest_events, limit): ids = await self.db_pool.runInteraction( "get_missing_events", self._get_missing_events, room_id, earliest_events, latest_events, limit, ) return await self.get_events_as_list(ids) def _get_missing_events(self, txn, room_id, earliest_events, latest_events, limit): seen_events = set(earliest_events) front = set(latest_events) - seen_events event_results = [] query = ("SELECT prev_event_id FROM event_edges " "WHERE room_id = ? AND event_id = ? AND is_state = ? " "LIMIT ?") while front and len(event_results) < limit: new_front = set() for event_id in front: txn.execute( query, (room_id, event_id, False, limit - len(event_results))) new_results = {t[0] for t in txn} - seen_events new_front |= new_results seen_events |= new_results event_results.extend(new_results) front = new_front # we built the list working backwards from latest_events; we now need to # reverse it so that the events are approximately chronological. event_results.reverse() return event_results async def get_successor_events(self, event_ids: Iterable[str]) -> List[str]: """Fetch all events that have the given events as a prev event Args: event_ids: The events to use as the previous events. """ rows = await self.db_pool.simple_select_many_batch( table="event_edges", column="prev_event_id", iterable=event_ids, retcols=("event_id", ), desc="get_successor_events", ) return [row["event_id"] for row in rows] @wrap_as_background_process("delete_old_forward_extrem_cache") async def _delete_old_forward_extrem_cache(self) -> None: def _delete_old_forward_extrem_cache_txn(txn): # Delete entries older than a month, while making sure we don't delete # the only entries for a room. sql = """ DELETE FROM stream_ordering_to_exterm WHERE room_id IN ( SELECT room_id FROM stream_ordering_to_exterm WHERE stream_ordering > ? ) AND stream_ordering < ? """ txn.execute(sql, (self.stream_ordering_month_ago, self.stream_ordering_month_ago)) await self.db_pool.runInteraction( "_delete_old_forward_extrem_cache", _delete_old_forward_extrem_cache_txn, )
class Cache(object): __slots__ = ( "cache", "name", "keylen", "thread", "metrics", "_pending_deferred_cache", ) def __init__( self, name: str, max_entries: int = 1000, keylen: int = 1, tree: bool = False, iterable: bool = False, apply_cache_factor_from_config: bool = True, ): """ Args: name: The name of the cache max_entries: Maximum amount of entries that the cache will hold keylen: The length of the tuple used as the cache key tree: Use a TreeCache instead of a dict as the underlying cache type iterable: If True, count each item in the cached object as an entry, rather than each cached object apply_cache_factor_from_config: Whether cache factors specified in the config file affect `max_entries` Returns: Cache """ cache_type = TreeCache if tree else dict self._pending_deferred_cache = cache_type() self.cache = LruCache( max_size=max_entries, keylen=keylen, cache_type=cache_type, size_callback=(lambda d: len(d)) if iterable else None, evicted_callback=self._on_evicted, apply_cache_factor_from_config=apply_cache_factor_from_config, ) self.name = name self.keylen = keylen self.thread = None self.metrics = register_cache( "cache", name, self.cache, collect_callback=self._metrics_collection_callback, ) @property def max_entries(self): return self.cache.max_size def _on_evicted(self, evicted_count): self.metrics.inc_evictions(evicted_count) def _metrics_collection_callback(self): cache_pending_metric.labels(self.name).set( len(self._pending_deferred_cache)) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread") def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True): """Looks the key up in the caches. Args: key(tuple) default: What is returned if key is not in the caches. If not specified then function throws KeyError instead callback(fn): Gets called when the entry in the cache is invalidated update_metrics (bool): whether to update the cache hit rate metrics Returns: Either an ObservableDeferred or the raw result """ callbacks = [callback] if callback else [] val = self._pending_deferred_cache.get(key, _CacheSentinel) if val is not _CacheSentinel: val.callbacks.update(callbacks) if update_metrics: self.metrics.inc_hits() return val.deferred val = self.cache.get(key, _CacheSentinel, callbacks=callbacks) if val is not _CacheSentinel: self.metrics.inc_hits() return val if update_metrics: self.metrics.inc_misses() if default is _CacheSentinel: raise KeyError() else: return default def set(self, key, value, callback=None): if not isinstance(value, defer.Deferred): raise TypeError("not a Deferred") callbacks = [callback] if callback else [] self.check_thread() observable = ObservableDeferred(value, consumeErrors=True) observer = defer.maybeDeferred(observable.observe) entry = CacheEntry(deferred=observable, callbacks=callbacks) existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry: existing_entry.invalidate() self._pending_deferred_cache[key] = entry def compare_and_pop(): """Check if our entry is still the one in _pending_deferred_cache, and if so, pop it. Returns true if the entries matched. """ existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry is entry: return True # oops, the _pending_deferred_cache has been updated since # we started our query, so we are out of date. # # Better put back whatever we took out. (We do it this way # round, rather than peeking into the _pending_deferred_cache # and then removing on a match, to make the common case faster) if existing_entry is not None: self._pending_deferred_cache[key] = existing_entry return False def cb(result): if compare_and_pop(): self.cache.set(key, result, entry.callbacks) else: # we're not going to put this entry into the cache, so need # to make sure that the invalidation callbacks are called. # That was probably done when _pending_deferred_cache was # updated, but it's possible that `set` was called without # `invalidate` being previously called, in which case it may # not have been. Either way, let's double-check now. entry.invalidate() def eb(_fail): compare_and_pop() entry.invalidate() # once the deferred completes, we can move the entry from the # _pending_deferred_cache to the real cache. # observer.addCallbacks(cb, eb) return observable def prefill(self, key, value, callback=None): callbacks = [callback] if callback else [] self.cache.set(key, value, callbacks=callbacks) def invalidate(self, key): self.check_thread() self.cache.pop(key, None) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, which will (a) stop it being returned # for future queries and (b) stop it being persisted as a proper entry # in self.cache. entry = self._pending_deferred_cache.pop(key, None) # run the invalidation callbacks now, rather than waiting for the # deferred to resolve. if entry: entry.invalidate() def invalidate_many(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError("The cache key must be a tuple not %r" % (type(key), )) self.cache.del_multi(key) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, as above entry_dict = self._pending_deferred_cache.pop(key, None) if entry_dict is not None: for entry in iterate_tree_cache_entry(entry_dict): entry.invalidate() def invalidate_all(self): self.check_thread() self.cache.clear() for entry in self._pending_deferred_cache.values(): entry.invalidate() self._pending_deferred_cache.clear()
class Cache(object): __slots__ = ( "cache", "max_entries", "name", "keylen", "thread", "metrics", "_pending_deferred_cache", ) def __init__(self, name, max_entries=1000, keylen=1, tree=False, iterable=False): cache_type = TreeCache if tree else dict self._pending_deferred_cache = cache_type() self.cache = LruCache( max_size=max_entries, keylen=keylen, cache_type=cache_type, size_callback=(lambda d: len(d)) if iterable else None, evicted_callback=self._on_evicted, ) self.name = name self.keylen = keylen self.thread = None self.metrics = register_cache("cache", name, self.cache) def _on_evicted(self, evicted_count): self.metrics.inc_evictions(evicted_count) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread") def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True): """Looks the key up in the caches. Args: key(tuple) default: What is returned if key is not in the caches. If not specified then function throws KeyError instead callback(fn): Gets called when the entry in the cache is invalidated update_metrics (bool): whether to update the cache hit rate metrics Returns: Either a Deferred or the raw result """ callbacks = [callback] if callback else [] val = self._pending_deferred_cache.get(key, _CacheSentinel) if val is not _CacheSentinel: val.callbacks.update(callbacks) if update_metrics: self.metrics.inc_hits() return val.deferred val = self.cache.get(key, _CacheSentinel, callbacks=callbacks) if val is not _CacheSentinel: self.metrics.inc_hits() return val if update_metrics: self.metrics.inc_misses() if default is _CacheSentinel: raise KeyError() else: return default def set(self, key, value, callback=None): callbacks = [callback] if callback else [] self.check_thread() entry = CacheEntry( deferred=value, callbacks=callbacks, ) existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry: existing_entry.invalidate() self._pending_deferred_cache[key] = entry def shuffle(result): existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry is entry: self.cache.set(key, result, entry.callbacks) else: # oops, the _pending_deferred_cache has been updated since # we started our query, so we are out of date. # # Better put back whatever we took out. (We do it this way # round, rather than peeking into the _pending_deferred_cache # and then removing on a match, to make the common case faster) if existing_entry is not None: self._pending_deferred_cache[key] = existing_entry # we're not going to put this entry into the cache, so need # to make sure that the invalidation callbacks are called. # That was probably done when _pending_deferred_cache was # updated, but it's possible that `set` was called without # `invalidate` being previously called, in which case it may # not have been. Either way, let's double-check now. entry.invalidate() return result entry.deferred.addCallback(shuffle) def prefill(self, key, value, callback=None): callbacks = [callback] if callback else [] self.cache.set(key, value, callbacks=callbacks) def invalidate(self, key): self.check_thread() self.cache.pop(key, None) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, which will (a) stop it being returned # for future queries and (b) stop it being persisted as a proper entry # in self.cache. entry = self._pending_deferred_cache.pop(key, None) # run the invalidation callbacks now, rather than waiting for the # deferred to resolve. if entry: entry.invalidate() def invalidate_many(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError("The cache key must be a tuple not %r" % (type(key), )) self.cache.del_multi(key) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, as above entry_dict = self._pending_deferred_cache.pop(key, None) if entry_dict is not None: for entry in iterate_tree_cache_entry(entry_dict): entry.invalidate() def invalidate_all(self): self.check_thread() self.cache.clear() for entry in itervalues(self._pending_deferred_cache): entry.invalidate() self._pending_deferred_cache.clear()
class Cache(object): __slots__ = ( "cache", "max_entries", "name", "keylen", "thread", "metrics", "_pending_deferred_cache", ) def __init__(self, name, max_entries=1000, keylen=1, tree=False, iterable=False): cache_type = TreeCache if tree else dict self._pending_deferred_cache = cache_type() self.cache = LruCache( max_size=max_entries, keylen=keylen, cache_type=cache_type, size_callback=(lambda d: len(d)) if iterable else None, evicted_callback=self._on_evicted, ) self.name = name self.keylen = keylen self.thread = None self.metrics = register_cache("cache", name, self.cache) def _on_evicted(self, evicted_count): self.metrics.inc_evictions(evicted_count) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread" ) def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True): """Looks the key up in the caches. Args: key(tuple) default: What is returned if key is not in the caches. If not specified then function throws KeyError instead callback(fn): Gets called when the entry in the cache is invalidated update_metrics (bool): whether to update the cache hit rate metrics Returns: Either a Deferred or the raw result """ callbacks = [callback] if callback else [] val = self._pending_deferred_cache.get(key, _CacheSentinel) if val is not _CacheSentinel: val.callbacks.update(callbacks) if update_metrics: self.metrics.inc_hits() return val.deferred val = self.cache.get(key, _CacheSentinel, callbacks=callbacks) if val is not _CacheSentinel: self.metrics.inc_hits() return val if update_metrics: self.metrics.inc_misses() if default is _CacheSentinel: raise KeyError() else: return default def set(self, key, value, callback=None): callbacks = [callback] if callback else [] self.check_thread() entry = CacheEntry( deferred=value, callbacks=callbacks, ) existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry: existing_entry.invalidate() self._pending_deferred_cache[key] = entry def shuffle(result): existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry is entry: self.cache.set(key, result, entry.callbacks) else: # oops, the _pending_deferred_cache has been updated since # we started our query, so we are out of date. # # Better put back whatever we took out. (We do it this way # round, rather than peeking into the _pending_deferred_cache # and then removing on a match, to make the common case faster) if existing_entry is not None: self._pending_deferred_cache[key] = existing_entry # we're not going to put this entry into the cache, so need # to make sure that the invalidation callbacks are called. # That was probably done when _pending_deferred_cache was # updated, but it's possible that `set` was called without # `invalidate` being previously called, in which case it may # not have been. Either way, let's double-check now. entry.invalidate() return result entry.deferred.addCallback(shuffle) def prefill(self, key, value, callback=None): callbacks = [callback] if callback else [] self.cache.set(key, value, callbacks=callbacks) def invalidate(self, key): self.check_thread() self.cache.pop(key, None) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, which will (a) stop it being returned # for future queries and (b) stop it being persisted as a proper entry # in self.cache. entry = self._pending_deferred_cache.pop(key, None) # run the invalidation callbacks now, rather than waiting for the # deferred to resolve. if entry: entry.invalidate() def invalidate_many(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError( "The cache key must be a tuple not %r" % (type(key),) ) self.cache.del_multi(key) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, as above entry_dict = self._pending_deferred_cache.pop(key, None) if entry_dict is not None: for entry in iterate_tree_cache_entry(entry_dict): entry.invalidate() def invalidate_all(self): self.check_thread() self.cache.clear() for entry in itervalues(self._pending_deferred_cache): entry.invalidate() self._pending_deferred_cache.clear()
class Cache(object): __slots__ = ( "cache", "max_entries", "name", "keylen", "sequence", "thread", "metrics", "_pending_deferred_cache", ) def __init__(self, name, max_entries=1000, keylen=1, tree=False, iterable=False): cache_type = TreeCache if tree else dict self._pending_deferred_cache = cache_type() self.cache = LruCache( max_size=max_entries, keylen=keylen, cache_type=cache_type, size_callback=(lambda d: len(d)) if iterable else None, ) self.name = name self.keylen = keylen self.sequence = 0 self.thread = None self.metrics = register_cache(name, self.cache) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread" ) def get(self, key, default=_CacheSentinel, callback=None, update_metrics=True): """Looks the key up in the caches. Args: key(tuple) default: What is returned if key is not in the caches. If not specified then function throws KeyError instead callback(fn): Gets called when the entry in the cache is invalidated update_metrics (bool): whether to update the cache hit rate metrics Returns: Either a Deferred or the raw result """ callbacks = [callback] if callback else [] val = self._pending_deferred_cache.get(key, _CacheSentinel) if val is not _CacheSentinel: if val.sequence == self.sequence: val.callbacks.update(callbacks) if update_metrics: self.metrics.inc_hits() return val.deferred val = self.cache.get(key, _CacheSentinel, callbacks=callbacks) if val is not _CacheSentinel: self.metrics.inc_hits() return val if update_metrics: self.metrics.inc_misses() if default is _CacheSentinel: raise KeyError() else: return default def set(self, key, value, callback=None): callbacks = [callback] if callback else [] self.check_thread() entry = CacheEntry( deferred=value, sequence=self.sequence, callbacks=callbacks, ) entry.callbacks.update(callbacks) existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry: existing_entry.invalidate() self._pending_deferred_cache[key] = entry def shuffle(result): if self.sequence == entry.sequence: existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry is entry: self.cache.set(key, result, entry.callbacks) else: entry.invalidate() else: entry.invalidate() return result entry.deferred.addCallback(shuffle) def prefill(self, key, value, callback=None): callbacks = [callback] if callback else [] self.cache.set(key, value, callbacks=callbacks) def invalidate(self, key): self.check_thread() # Increment the sequence number so that any SELECT statements that # raced with the INSERT don't update the cache (SYN-369) self.sequence += 1 entry = self._pending_deferred_cache.pop(key, None) if entry: entry.invalidate() self.cache.pop(key, None) def invalidate_many(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError( "The cache key must be a tuple not %r" % (type(key),) ) self.sequence += 1 self.cache.del_multi(key) entry_dict = self._pending_deferred_cache.pop(key, None) if entry_dict is not None: for entry in iterate_tree_cache_entry(entry_dict): entry.invalidate() def invalidate_all(self): self.check_thread() self.sequence += 1 self.cache.clear()
class DeferredCache(Generic[KT, VT]): """Wraps an LruCache, adding support for Deferred results. It expects that each entry added with set() will be a Deferred; likewise get() will return a Deferred. """ __slots__ = ( "cache", "thread", "_pending_deferred_cache", ) def __init__( self, name: str, max_entries: int = 1000, tree: bool = False, iterable: bool = False, apply_cache_factor_from_config: bool = True, ): """ Args: name: The name of the cache max_entries: Maximum amount of entries that the cache will hold keylen: The length of the tuple used as the cache key. Ignored unless `tree` is True. tree: Use a TreeCache instead of a dict as the underlying cache type iterable: If True, count each item in the cached object as an entry, rather than each cached object apply_cache_factor_from_config: Whether cache factors specified in the config file affect `max_entries` """ cache_type = TreeCache if tree else dict # _pending_deferred_cache maps from the key value to a `CacheEntry` object. self._pending_deferred_cache = ( cache_type() ) # type: Union[TreeCache, MutableMapping[KT, CacheEntry]] def metrics_cb(): cache_pending_metric.labels(name).set(len(self._pending_deferred_cache)) # cache is used for completed results and maps to the result itself, rather than # a Deferred. self.cache = LruCache( max_size=max_entries, cache_name=name, cache_type=cache_type, size_callback=(lambda d: len(d) or 1) if iterable else None, metrics_collection_callback=metrics_cb, apply_cache_factor_from_config=apply_cache_factor_from_config, ) # type: LruCache[KT, VT] self.thread = None # type: Optional[threading.Thread] @property def max_entries(self): return self.cache.max_size def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread" ) def get( self, key: KT, callback: Optional[Callable[[], None]] = None, update_metrics: bool = True, ) -> defer.Deferred: """Looks the key up in the caches. For symmetry with set(), this method does *not* follow the synapse logcontext rules: the logcontext will not be cleared on return, and the Deferred will run its callbacks in the sentinel context. In other words: wrap the result with make_deferred_yieldable() before `await`ing it. Args: key: callback: Gets called when the entry in the cache is invalidated update_metrics (bool): whether to update the cache hit rate metrics Returns: A Deferred which completes with the result. Note that this may later fail if there is an ongoing set() operation which later completes with a failure. Raises: KeyError if the key is not found in the cache """ callbacks = [callback] if callback else [] val = self._pending_deferred_cache.get(key, _Sentinel.sentinel) if val is not _Sentinel.sentinel: val.callbacks.update(callbacks) if update_metrics: m = self.cache.metrics assert m # we always have a name, so should always have metrics m.inc_hits() return val.deferred.observe() val2 = self.cache.get( key, _Sentinel.sentinel, callbacks=callbacks, update_metrics=update_metrics ) if val2 is _Sentinel.sentinel: raise KeyError() else: return defer.succeed(val2) def get_immediate( self, key: KT, default: T, update_metrics: bool = True ) -> Union[VT, T]: """If we have a *completed* cached value, return it.""" return self.cache.get(key, default, update_metrics=update_metrics) def set( self, key: KT, value: defer.Deferred, callback: Optional[Callable[[], None]] = None, ) -> defer.Deferred: """Adds a new entry to the cache (or updates an existing one). The given `value` *must* be a Deferred. First any existing entry for the same key is invalidated. Then a new entry is added to the cache for the given key. Until the `value` completes, calls to `get()` for the key will also result in an incomplete Deferred, which will ultimately complete with the same result as `value`. If `value` completes successfully, subsequent calls to `get()` will then return a completed deferred with the same result. If it *fails*, the cache is invalidated and subequent calls to `get()` will raise a KeyError. If another call to `set()` happens before `value` completes, then (a) any invalidation callbacks registered in the interim will be called, (b) any `get()`s in the interim will continue to complete with the result from the *original* `value`, (c) any future calls to `get()` will complete with the result from the *new* `value`. It is expected that `value` does *not* follow the synapse logcontext rules - ie, if it is incomplete, it runs its callbacks in the sentinel context. Args: key: Key to be set value: a deferred which will complete with a result to add to the cache callback: An optional callback to be called when the entry is invalidated """ if not isinstance(value, defer.Deferred): raise TypeError("not a Deferred") callbacks = [callback] if callback else [] self.check_thread() existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry: existing_entry.invalidate() # XXX: why don't we invalidate the entry in `self.cache` yet? # we can save a whole load of effort if the deferred is ready. if value.called: result = value.result if not isinstance(result, failure.Failure): self.cache.set(key, result, callbacks) return value # otherwise, we'll add an entry to the _pending_deferred_cache for now, # and add callbacks to add it to the cache properly later. observable = ObservableDeferred(value, consumeErrors=True) observer = observable.observe() entry = CacheEntry(deferred=observable, callbacks=callbacks) self._pending_deferred_cache[key] = entry def compare_and_pop(): """Check if our entry is still the one in _pending_deferred_cache, and if so, pop it. Returns true if the entries matched. """ existing_entry = self._pending_deferred_cache.pop(key, None) if existing_entry is entry: return True # oops, the _pending_deferred_cache has been updated since # we started our query, so we are out of date. # # Better put back whatever we took out. (We do it this way # round, rather than peeking into the _pending_deferred_cache # and then removing on a match, to make the common case faster) if existing_entry is not None: self._pending_deferred_cache[key] = existing_entry return False def cb(result): if compare_and_pop(): self.cache.set(key, result, entry.callbacks) else: # we're not going to put this entry into the cache, so need # to make sure that the invalidation callbacks are called. # That was probably done when _pending_deferred_cache was # updated, but it's possible that `set` was called without # `invalidate` being previously called, in which case it may # not have been. Either way, let's double-check now. entry.invalidate() def eb(_fail): compare_and_pop() entry.invalidate() # once the deferred completes, we can move the entry from the # _pending_deferred_cache to the real cache. # observer.addCallbacks(cb, eb) # we return a new Deferred which will be called before any subsequent observers. return observable.observe() def prefill( self, key: KT, value: VT, callback: Optional[Callable[[], None]] = None ): callbacks = [callback] if callback else [] self.cache.set(key, value, callbacks=callbacks) def invalidate(self, key): """Delete a key, or tree of entries If the cache is backed by a regular dict, then "key" must be of the right type for this cache If the cache is backed by a TreeCache, then "key" must be a tuple, but may be of lower cardinality than the TreeCache - in which case the whole subtree is deleted. """ self.check_thread() self.cache.del_multi(key) # if we have a pending lookup for this key, remove it from the # _pending_deferred_cache, which will (a) stop it being returned # for future queries and (b) stop it being persisted as a proper entry # in self.cache. entry = self._pending_deferred_cache.pop(key, None) # run the invalidation callbacks now, rather than waiting for the # deferred to resolve. if entry: # _pending_deferred_cache.pop should either return a CacheEntry, or, in the # case of a TreeCache, a dict of keys to cache entries. Either way calling # iterate_tree_cache_entry on it will do the right thing. for entry in iterate_tree_cache_entry(entry): entry.invalidate() def invalidate_all(self): self.check_thread() self.cache.clear() for entry in self._pending_deferred_cache.values(): entry.invalidate() self._pending_deferred_cache.clear()
class ClientIpStore(ClientIpWorkerStore): def __init__(self, database: DatabasePool, db_conn, hs): self.client_ip_last_seen = LruCache(cache_name="client_ip_last_seen", keylen=4, max_size=50000) super().__init__(database, db_conn, hs) # (user_id, access_token, ip,) -> (user_agent, device_id, last_seen) self._batch_row_update = {} self._client_ip_looper = self._clock.looping_call( self._update_client_ips_batch, 5 * 1000) self.hs.get_reactor().addSystemEventTrigger( "before", "shutdown", self._update_client_ips_batch) async def insert_client_ip(self, user_id, access_token, ip, user_agent, device_id, now=None): if not now: now = int(self._clock.time_msec()) key = (user_id, access_token, ip) try: last_seen = self.client_ip_last_seen.get(key) except KeyError: last_seen = None await self.populate_monthly_active_users(user_id) # Rate-limited inserts if last_seen is not None and (now - last_seen) < LAST_SEEN_GRANULARITY: return self.client_ip_last_seen.set(key, now) self._batch_row_update[key] = (user_agent, device_id, now) @wrap_as_background_process("update_client_ips") async def _update_client_ips_batch(self) -> None: # If the DB pool has already terminated, don't try updating if not self.db_pool.is_running(): return to_update = self._batch_row_update self._batch_row_update = {} await self.db_pool.runInteraction("_update_client_ips_batch", self._update_client_ips_batch_txn, to_update) def _update_client_ips_batch_txn(self, txn, to_update): if "user_ips" in self.db_pool._unsafe_to_upsert_tables or ( not self.database_engine.can_native_upsert): self.database_engine.lock_table(txn, "user_ips") for entry in to_update.items(): (user_id, access_token, ip), (user_agent, device_id, last_seen) = entry try: self.db_pool.simple_upsert_txn( txn, table="user_ips", keyvalues={ "user_id": user_id, "access_token": access_token, "ip": ip, }, values={ "user_agent": user_agent, "device_id": device_id, "last_seen": last_seen, }, lock=False, ) # Technically an access token might not be associated with # a device so we need to check. if device_id: # this is always an update rather than an upsert: the row should # already exist, and if it doesn't, that may be because it has been # deleted, and we don't want to re-create it. self.db_pool.simple_update_txn( txn, table="devices", keyvalues={ "user_id": user_id, "device_id": device_id }, updatevalues={ "user_agent": user_agent, "last_seen": last_seen, "ip": ip, }, ) except Exception as e: # Failed to upsert, log and continue logger.error("Failed to insert client IP %r: %r", entry, e) async def get_last_client_ip_by_device( self, user_id: str, device_id: Optional[str]) -> Dict[Tuple[str, str], dict]: """For each device_id listed, give the user_ip it was last seen on Args: user_id: The user to fetch devices for. device_id: If None fetches all devices for the user Returns: A dictionary mapping a tuple of (user_id, device_id) to dicts, with keys giving the column names from the devices table. """ keyvalues = {"user_id": user_id} if device_id is not None: keyvalues["device_id"] = device_id res = await self.db_pool.simple_select_list( table="devices", keyvalues=keyvalues, retcols=("user_id", "ip", "user_agent", "device_id", "last_seen"), ) ret = {(d["user_id"], d["device_id"]): d for d in res} for key in self._batch_row_update: uid, access_token, ip = key if uid == user_id: user_agent, did, last_seen = self._batch_row_update[key] if not device_id or did == device_id: ret[(user_id, device_id)] = { "user_id": user_id, "access_token": access_token, "ip": ip, "user_agent": user_agent, "device_id": did, "last_seen": last_seen, } return ret async def get_user_ip_and_agents(self, user): user_id = user.to_string() results = {} for key in self._batch_row_update: uid, access_token, ip, = key if uid == user_id: user_agent, _, last_seen = self._batch_row_update[key] results[(access_token, ip)] = (user_agent, last_seen) rows = await self.db_pool.simple_select_list( table="user_ips", keyvalues={"user_id": user_id}, retcols=["access_token", "ip", "user_agent", "last_seen"], desc="get_user_ip_and_agents", ) results.update(((row["access_token"], row["ip"]), (row["user_agent"], row["last_seen"])) for row in rows) return [{ "access_token": access_token, "ip": ip, "user_agent": user_agent, "last_seen": last_seen, } for (access_token, ip), (user_agent, last_seen) in results.items()]
class ClientIpStore(ClientIpWorkerStore): def __init__(self, database: DatabasePool, db_conn, hs): self.client_ip_last_seen = LruCache( cache_name="client_ip_last_seen", max_size=50000 ) super().__init__(database, db_conn, hs) # (user_id, access_token, ip,) -> (user_agent, device_id, last_seen) self._batch_row_update = {} self._client_ip_looper = self._clock.looping_call( self._update_client_ips_batch, 5 * 1000 ) self.hs.get_reactor().addSystemEventTrigger( "before", "shutdown", self._update_client_ips_batch ) async def insert_client_ip( self, user_id, access_token, ip, user_agent, device_id, now=None ): if not now: now = int(self._clock.time_msec()) key = (user_id, access_token, ip) try: last_seen = self.client_ip_last_seen.get(key) except KeyError: last_seen = None await self.populate_monthly_active_users(user_id) # Rate-limited inserts if last_seen is not None and (now - last_seen) < LAST_SEEN_GRANULARITY: return self.client_ip_last_seen.set(key, now) self._batch_row_update[key] = (user_agent, device_id, now) @wrap_as_background_process("update_client_ips") async def _update_client_ips_batch(self) -> None: # If the DB pool has already terminated, don't try updating if not self.db_pool.is_running(): return to_update = self._batch_row_update self._batch_row_update = {} await self.db_pool.runInteraction( "_update_client_ips_batch", self._update_client_ips_batch_txn, to_update ) def _update_client_ips_batch_txn(self, txn, to_update): if "user_ips" in self.db_pool._unsafe_to_upsert_tables or ( not self.database_engine.can_native_upsert ): self.database_engine.lock_table(txn, "user_ips") for entry in to_update.items(): (user_id, access_token, ip), (user_agent, device_id, last_seen) = entry self.db_pool.simple_upsert_txn( txn, table="user_ips", keyvalues={"user_id": user_id, "access_token": access_token, "ip": ip}, values={ "user_agent": user_agent, "device_id": device_id, "last_seen": last_seen, }, lock=False, ) # Technically an access token might not be associated with # a device so we need to check. if device_id: # this is always an update rather than an upsert: the row should # already exist, and if it doesn't, that may be because it has been # deleted, and we don't want to re-create it. self.db_pool.simple_update_txn( txn, table="devices", keyvalues={"user_id": user_id, "device_id": device_id}, updatevalues={ "user_agent": user_agent, "last_seen": last_seen, "ip": ip, }, ) async def get_last_client_ip_by_device( self, user_id: str, device_id: Optional[str] ) -> Dict[Tuple[str, str], dict]: """For each device_id listed, give the user_ip it was last seen on Args: user_id: The user to fetch devices for. device_id: If None fetches all devices for the user Returns: A dictionary mapping a tuple of (user_id, device_id) to dicts, with keys giving the column names from the devices table. """ ret = await super().get_last_client_ip_by_device(user_id, device_id) # Update what is retrieved from the database with data which is pending # insertion, as if it has already been stored in the database. for key in self._batch_row_update: uid, _access_token, ip = key if uid == user_id: user_agent, did, last_seen = self._batch_row_update[key] if did is None: # These updates don't make it to the `devices` table continue if not device_id or did == device_id: ret[(user_id, did)] = { "user_id": user_id, "ip": ip, "user_agent": user_agent, "device_id": did, "last_seen": last_seen, } return ret async def get_user_ip_and_agents( self, user: UserID, since_ts: int = 0 ) -> List[Dict[str, Union[str, int]]]: """ Fetch IP/User Agent connection since a given timestamp. """ user_id = user.to_string() results = {} for key in self._batch_row_update: ( uid, access_token, ip, ) = key if uid == user_id: user_agent, _, last_seen = self._batch_row_update[key] if last_seen >= since_ts: results[(access_token, ip)] = (user_agent, last_seen) def get_recent(txn): txn.execute( """ SELECT access_token, ip, user_agent, last_seen FROM user_ips WHERE last_seen >= ? AND user_id = ? ORDER BY last_seen DESC """, (since_ts, user_id), ) return txn.fetchall() rows = await self.db_pool.runInteraction( desc="get_user_ip_and_agents", func=get_recent ) results.update( ((access_token, ip), (user_agent, last_seen)) for access_token, ip, user_agent, last_seen in rows ) return [ { "access_token": access_token, "ip": ip, "user_agent": user_agent, "last_seen": last_seen, } for (access_token, ip), (user_agent, last_seen) in results.items() ]
class Cache(object): __slots__ = ( "cache", "max_entries", "name", "keylen", "sequence", "thread", "metrics", ) def __init__(self, name, max_entries=1000, keylen=1, tree=False): cache_type = TreeCache if tree else dict self.cache = LruCache( max_size=max_entries, keylen=keylen, cache_type=cache_type ) self.name = name self.keylen = keylen self.sequence = 0 self.thread = None self.metrics = register_cache(name, self.cache) def check_thread(self): expected_thread = self.thread if expected_thread is None: self.thread = threading.current_thread() else: if expected_thread is not threading.current_thread(): raise ValueError( "Cache objects can only be accessed from the main thread" ) def get(self, key, default=_CacheSentinel, callback=None): val = self.cache.get(key, _CacheSentinel, callback=callback) if val is not _CacheSentinel: self.metrics.inc_hits() return val self.metrics.inc_misses() if default is _CacheSentinel: raise KeyError() else: return default def update(self, sequence, key, value, callback=None): self.check_thread() if self.sequence == sequence: # Only update the cache if the caches sequence number matches the # number that the cache had before the SELECT was started (SYN-369) self.prefill(key, value, callback=callback) def prefill(self, key, value, callback=None): self.cache.set(key, value, callback=callback) def invalidate(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError( "The cache key must be a tuple not %r" % (type(key),) ) # Increment the sequence number so that any SELECT statements that # raced with the INSERT don't update the cache (SYN-369) self.sequence += 1 self.cache.pop(key, None) def invalidate_many(self, key): self.check_thread() if not isinstance(key, tuple): raise TypeError( "The cache key must be a tuple not %r" % (type(key),) ) self.sequence += 1 self.cache.del_multi(key) def invalidate_all(self): self.check_thread() self.sequence += 1 self.cache.clear()