def _get_next_session_id_via_pipeline(self, pipeline: Pipeline) -> int: # Do this in a loop to account for (unlikely) possibility that someone manually used a key out of order session_id = None while session_id is None: # Get a session id, base on stored (or initialized) value at _next_session_id_key, then bump said value # Remember, Redis persists strings (though it can implicitly convert from int to string on its side) session_id_str: Optional[str] = pipeline.get(self._next_session_id_key) if session_id_str is None: session_id = self.get_initial_session_id_value() pipeline.set(self._next_session_id_key, session_id + 1) else: session_id = int(session_id_str) pipeline.incr(self._next_session_id_key, 1) # However, if the key is already in use (via manual selection), we have to try again if pipeline.hlen(self.get_key_for_session_by_id(session_id)) != 0: session_id = None return session_id
def cache_teams(pipe: Pipeline) -> None: """ Put "teams" table data from database to cache. Just adds commands to pipeline stack, don't forget to execute afterwards. """ with utils.db_cursor(dict_cursor=True) as (_, curs): curs.execute(models.Team.get_select_active_query()) teams = curs.fetchall() teams = list(models.Team.from_dict(team) for team in teams) key = CacheKeys.teams() pipe.delete(key) if teams: pipe.sadd(key, *[team.to_json() for team in teams]) for team in teams: pipe.set(CacheKeys.team_by_token(team.token), team.id)
def cache_last_flags(current_round: int, pipe: Pipeline) -> None: """ Cache all generated flags from last "flag_lifetime" rounds. Just adds commands to pipeline stack, don't forget to execute afterwards. :param current_round: current round :param pipe: redis connection to add command to """ game_config = game.get_current_game_config() expires = game_config.flag_lifetime * game_config.round_time * 2 with utils.db_cursor(dict_cursor=True) as (_, curs): curs.execute( _SELECT_ALL_LAST_FLAGS_QUERY, {'round': current_round - game_config.flag_lifetime}, ) flags = curs.fetchall() flag_models = list(models.Flag.from_dict(data) for data in flags) pipe.set(CacheKeys.flags_cached(), 1) for flag in flag_models: pipe.set(CacheKeys.flag_by_id(flag.id), flag.to_json(), ex=expires) pipe.set(CacheKeys.flag_by_str(flag.flag), flag.to_json(), ex=expires)
def redis_set_query_pipe(pipe: Pipeline, name: str, value: str, expire: int, db: int) -> List: try: pipe.execute_command('SELECT', db) pipe.set(name=name, value=value, ex=expire) except WatchError: logger.error(exc_info=True)
def cache_game_config(pipe: Pipeline) -> None: """Put game config to cache (without round or game_running).""" game_config = game.get_db_game_config() data = game_config.to_json() pipe.set(CacheKeys.game_config(), data)