__init__.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import asyncio
  2. import collections
  3. import logging
  4. import random
  5. from typing import List, Tuple, Dict, Union
  6. from .random_street_view import call_random_street_view, VALID_COUNTRIES as RSV_COUNTRIES
  7. from .urban_centers import urban_coord, VALID_COUNTRIES as URBAN_COUNTRIES
  8. from .shared import aiohttp_client
  9. from ..schemas import GameConfig, GenMethodEnum, CountryCode, CacheInfo, GeneratorInfo
  10. logger = logging.getLogger(__name__)
  11. generator_info = [
  12. GeneratorInfo(
  13. generation_method=GenMethodEnum.rsv,
  14. country_locks=RSV_COUNTRIES
  15. ),
  16. GeneratorInfo(
  17. generation_method=GenMethodEnum.urban,
  18. country_locks=URBAN_COUNTRIES
  19. ),
  20. ]
  21. cache_names = {
  22. GenMethodEnum.rsv: "RSV",
  23. GenMethodEnum.urban: "Urban",
  24. }
  25. class ExhaustedSourceError(Exception):
  26. pass
  27. class PointStore:
  28. def __init__(self,
  29. cache_targets: Dict[Tuple[GenMethodEnum, CountryCode], int],
  30. rsv_country_retries: int = 5,
  31. urban_country_pool_size: int = 30,
  32. urban_country_retries: int = 30,
  33. urban_city_retries: int = 50,
  34. urban_city_retries_per_random_country: int = 10):
  35. self.cache_targets = cache_targets
  36. self.rsv_country_retries = rsv_country_retries
  37. self.urban_country_pool_size = urban_country_pool_size
  38. self.urban_country_retries = urban_country_retries
  39. self.urban_city_retries = urban_city_retries
  40. self.urban_city_retries_per_random_country = urban_city_retries_per_random_country
  41. self.store = collections.defaultdict(collections.deque)
  42. async def _gen_rsv_point(self, country: CountryCode):
  43. # RSV point function returns a collection of points, which should be cached
  44. points = await call_random_street_view(country)
  45. if len(points) > 0:
  46. point = points.pop()
  47. self.store[(GenMethodEnum.rsv, country)].extend(points)
  48. return point
  49. async def _gen_urban_point(self, countries: List[CountryCode], city_retries: int):
  50. for country in countries:
  51. logger.info(f"Selecting urban centers from {country}")
  52. pt = await urban_coord(country, city_retries=city_retries)
  53. if pt is not None:
  54. return pt
  55. async def get_point(self, generator: GenMethodEnum, country: Union[CountryCode, None], force_generate: bool = False) -> Tuple[str, float, float]:
  56. if country is None:
  57. # generating points across the whole world
  58. # for current generators, this means selecting a country at random
  59. if generator == GenMethodEnum.rsv:
  60. for _ in range(self.rsv_country_retries):
  61. # try a few countries before giving up, just in case one has no data
  62. country = random.choice(RSV_COUNTRIES)
  63. point = await self._gen_rsv_point(country)
  64. if point is not None:
  65. return point
  66. elif generator == GenMethodEnum.urban:
  67. # try many countries since finding an urban center point is harder
  68. countries = random.sample(URBAN_COUNTRIES, k=min(self.urban_country_pool_size, len(URBAN_COUNTRIES)))
  69. point = await self._gen_urban_point(countries, self.urban_city_retries_per_random_country)
  70. if point is not None:
  71. return point
  72. # if nothing could be done - inform the caller
  73. raise ExhaustedSourceError
  74. # generating points for a specific country
  75. # if we already have a point ready, just return it immediately
  76. if not force_generate:
  77. stock = self.store[(generator, country)]
  78. if len(stock) > 0:
  79. return stock.popleft()
  80. # otherwise, need to actually generate a new point
  81. if generator == GenMethodEnum.rsv:
  82. point = await self._gen_rsv_point(country)
  83. if point is not None:
  84. return point
  85. elif generator == GenMethodEnum.urban:
  86. point = await self._gen_urban_point((country for _ in range(self.urban_country_retries)), self.urban_city_retries)
  87. if point is not None:
  88. return point
  89. # finally, if all that fails, just inform the caller
  90. raise ExhaustedSourceError
  91. async def get_points(self, config: GameConfig) -> List[Tuple[str, float, float]]:
  92. """
  93. Provide points according to the GameConfig.
  94. Return a list of valid geo points, as
  95. (2 character country code, latitude, longitude) tuples.
  96. In the event that the configured source cannot reasonably supply enough points,
  97. most likely due to time constraints, this will raise an ExhaustedSourceError.
  98. """
  99. try:
  100. point_tasks = [self.get_point(config.generation_method, config.country_lock) for _ in range(config.rounds)]
  101. gathered = asyncio.gather(*point_tasks)
  102. return await asyncio.wait_for(gathered, 60)
  103. # TODO - it would be nice to keep partially generated sets around if there's a timeout or exhaustion
  104. except asyncio.TimeoutError:
  105. raise ExhaustedSourceError
  106. def get_cache_info(self) -> List[CacheInfo]:
  107. """
  108. Get CacheInfo for all caches.
  109. """
  110. return [CacheInfo(cache_name=f"{cache_names[g]}-{c}", size=len(ps)) for (g, c), ps in self.store.items()]
  111. async def _restock_source_impl(self, generator: GenMethodEnum, country: CountryCode):
  112. key = (generator, country)
  113. target = self.cache_targets.get(key, 0)
  114. stock = self.store[key]
  115. while len(stock) < target: # this check allows for RSV to do its multi-point restock
  116. stock.append(await self.get_point(*key, force_generate=True))
  117. async def restock_source(self, config: GameConfig):
  118. """
  119. Restock any caches associated with the GameConfig.
  120. """
  121. if config.country_lock is None:
  122. return
  123. try:
  124. await self._restock_source_impl(config.generation_method, config.country_lock)
  125. except ExhaustedSourceError:
  126. # if the cache can't be restocked, that is bad, but not fatal
  127. logger.exception(f"Failed to fully restock point cache for {config}")
  128. async def restock_all(self, timeout: Union[int, float, None] = None):
  129. """
  130. Restock all caches.
  131. """
  132. restock_tasks = [self._restock_source_impl(gen, cc) for (gen, cc) in self.cache_targets.keys()]
  133. gathered = asyncio.gather(*restock_tasks)
  134. try:
  135. await asyncio.wait_for(gathered, timeout)
  136. except (asyncio.TimeoutError, ExhaustedSourceError):
  137. # if this task times out, it's fine, as it's just intended to be a best effort
  138. logger.exception(f"Failed to fully restock point cache for {config}")
  139. points = PointStore({
  140. (GenMethodEnum.urban, "us"): 10,
  141. })