A VCS repository archival tool
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

284 lines
10 KiB

  1. import abc
  2. import collections
  3. #import codearchiver.modules # In get_module_class
  4. import codearchiver.version
  5. import dataclasses
  6. import logging
  7. import queue
  8. import requests
  9. import time
  10. import typing
  11. import weakref
  12. logger = logging.getLogger(__name__)
  13. class InputURL:
  14. '''
  15. An input URL
  16. This primarily exists so multiple modules can access the content behind the URL for checks in `Module.matches` without fetching multiple times.
  17. It also handles the module name prefix in the scheme part of the URL. Note that `InputURL.url` is then the part without the module name.
  18. '''
  19. def __init__(self, url: str):
  20. if 0 < url.find('+') < url.find('://'):
  21. # '+' and '://' appear in the URL in this order and there is at least one character each before the + as well as between the two
  22. self._moduleScheme, self._url = url.split('+', 1)
  23. else:
  24. self._moduleScheme = None
  25. self._url = url
  26. self._response = None
  27. @property
  28. def url(self) -> str:
  29. '''URL without the module scheme prefix (if any)'''
  30. return self._url
  31. @property
  32. def moduleScheme(self) -> typing.Optional[str]:
  33. '''Module scheme prefix (if one is included, else `None`)'''
  34. return self._moduleScheme
  35. @property
  36. def content(self) -> str:
  37. '''HTTP response body upon fetching the URL with GET'''
  38. if self._response is None:
  39. self._response = HttpClient().get(self.url)
  40. return self._response.text
  41. def __repr__(self):
  42. return f'{type(self).__module__}.{type(self).__name__}({self._url!r})'
  43. @dataclasses.dataclass
  44. class Result:
  45. '''Container for the result of a module'''
  46. id: str
  47. '''A unique ID for this result'''
  48. files: typing.List[str] = dataclasses.field(default_factory = list)
  49. '''List of filenames produced by the run'''
  50. submoduleResults: typing.List[typing.Tuple['Module', 'Result']] = dataclasses.field(default_factory = list)
  51. '''List of related submodules and their results'''
  52. class HttpError(Exception):
  53. '''An HTTP request failed too many times.'''
  54. class HttpClient:
  55. '''A thin wrapper HTTP client around Requests with exponential backoff retries and a default user agent for all requests.'''
  56. defaultRetries: int = 3
  57. '''Default number of retries on errors unless overridden on creating the HttpClient object'''
  58. defaultUserAgent: str = f'codearchiver/{codearchiver.version.__version__}'
  59. '''Default user agent unless overridden on instantiation or by overriding via the headers kwarg'''
  60. def __init__(self, retries: typing.Optional[int] = None, userAgent: typing.Optional[str] = None):
  61. self._session = requests.Session()
  62. self._retries = retries if retries else self.defaultRetries
  63. self._userAgent = userAgent if userAgent else self.defaultUserAgent
  64. def request(self,
  65. method,
  66. url,
  67. params = None,
  68. data = None,
  69. headers: typing.Optional[typing.Dict[str, str]] = None,
  70. timeout: int = 10,
  71. responseOkCallback: typing.Optional[typing.Callable[[requests.Response], typing.Tuple[bool, typing.Optional[str]]]] = None,
  72. ) -> requests.Response:
  73. '''
  74. Make an HTTP request
  75. For the details on `method`, `url`, `params`, and `data`, refer to the Requests documentation on the constructor of `requests.Request`.
  76. For details on `timeout`, see `requests.adapters.HTTPAdapter.send`.
  77. `headers` can be used to specify any HTTP headers. Note that this is case-sensitive. To override the user agent, include a value for the `User-Agent` key here.
  78. `responseOkCallback` can be used to control whether a response is considered acceptable or not. By default, all HTTP responses are considered fine. If specified, this callable must produce a boolean marking whether the response is successful and an error message string. The string is used for logging purposes when the success flag is `False`; it should be `None` if the first return value is `True`.
  79. '''
  80. mergedHeaders = {'User-Agent': self._userAgent}
  81. if headers:
  82. mergedHeaders.update(headers)
  83. headers = mergedHeaders
  84. for attempt in range(self._retries + 1):
  85. # The request is newly prepared on each retry because of potential cookie updates.
  86. req = self._session.prepare_request(requests.Request(method, url, params = params, data = data, headers = headers))
  87. logger.info(f'Retrieving {req.url}')
  88. logger.debug(f'... with headers: {headers!r}')
  89. if data:
  90. logger.debug(f'... with data: {data!r}')
  91. try:
  92. r = self._session.send(req, timeout = timeout)
  93. except requests.exceptions.RequestException as exc:
  94. if attempt < self._retries:
  95. retrying = ', retrying'
  96. level = logging.WARNING
  97. else:
  98. retrying = ''
  99. level = logging.ERROR
  100. logger.log(level, f'Error retrieving {req.url}: {exc!r}{retrying}')
  101. else:
  102. if responseOkCallback is not None:
  103. success, msg = responseOkCallback(r)
  104. else:
  105. success, msg = (True, None)
  106. msg = f': {msg}' if msg else ''
  107. if success:
  108. logger.debug(f'{req.url} retrieved successfully{msg}')
  109. return r
  110. else:
  111. if attempt < self._retries:
  112. retrying = ', retrying'
  113. level = logging.WARNING
  114. else:
  115. retrying = ''
  116. level = logging.ERROR
  117. logger.log(level, f'Error retrieving {req.url}{msg}{retrying}')
  118. if attempt < self._retries:
  119. sleepTime = 1.0 * 2**attempt # exponential backoff: sleep 1 second after first attempt, 2 after second, 4 after third, etc.
  120. logger.info(f'Waiting {sleepTime:.0f} seconds')
  121. time.sleep(sleepTime)
  122. else:
  123. msg = f'{self._retries + 1} requests to {req.url} failed, giving up.'
  124. logger.fatal(msg)
  125. raise HttpError(msg)
  126. raise RuntimeError('Reached unreachable code')
  127. def get(self, *args, **kwargs):
  128. '''Make a GET request. This is equivalent to calling `.request('GET', ...)`.'''
  129. return self.request('GET', *args, **kwargs)
  130. def post(self, *args, **kwargs):
  131. '''Make a POST request. This is equivalent to calling `.request('POST', ...)`.'''
  132. return self.request('POST', *args, **kwargs)
  133. class ModuleMeta(type):
  134. '''Metaclass of modules. This is used to keep track of which modules exist and selecting them. It also enforces module name restrictions and prevents name collisions.'''
  135. __modulesByName: typing.Dict[str, typing.Type['Module']] = {}
  136. def __new__(cls, *args, **kwargs):
  137. class_ = super().__new__(cls, *args, **kwargs)
  138. if class_.name is not None:
  139. if class_.name.strip('abcdefghijklmnopqrstuvwxyz_-') != '':
  140. raise RuntimeError(f'Invalid class name: {class_.name!r}')
  141. if class_.name in cls.__modulesByName:
  142. raise RuntimeError(f'Class name collision: {class_.name!r} is already known')
  143. cls.__modulesByName[class_.name] = weakref.ref(class_)
  144. logger.info(f'Found {class_.name!r} module {class_.__module__}.{class_.__name__}')
  145. else:
  146. logger.info(f'Found nameless module {class_.__module__}.{class_.__name__}')
  147. return class_
  148. @classmethod
  149. def get_module_by_name(cls, name: str) -> typing.Optional[typing.Type['Module']]:
  150. '''Get a module by name if one exists'''
  151. if classRef := cls.__modulesByName.get(name):
  152. class_ = classRef()
  153. if class_ is None:
  154. logger.info(f'Module {name!r} is gone, dropping')
  155. del cls.__modulesByName[name]
  156. return class_
  157. @classmethod
  158. def iter_modules(cls) -> typing.Iterator[typing.Type['Module']]:
  159. '''Iterate over all known modules'''
  160. # Housekeeping first: remove dead modules
  161. for name in list(cls.__modulesByName): # create a copy of the names list so the dict can be modified in the loop
  162. if cls.__modulesByName[name]() is None:
  163. logger.info(f'Module {name!r} is gone, dropping')
  164. del cls.__modulesByName[name]
  165. for name, classRef in cls.__modulesByName.items():
  166. class_ = classRef()
  167. if class_ is None:
  168. # Module class no longer exists, skip
  169. # Even though dead modules are removed above, it's possible that the code consuming this iterator drops/deletes modules.
  170. continue
  171. yield class_
  172. @classmethod
  173. def drop(cls, module: 'Module'):
  174. '''
  175. Remove a module from the list of known modules
  176. If a Module subclass is destroyed after `del MyModule`, it is also eventually removed from the list. However, as that relies on garbage collection, it should not be depended on and modules should be dropped with this method explicitly.
  177. '''
  178. if module.name is not None and module.name in cls.__modulesByName:
  179. del cls.__modulesByName[module.name]
  180. logger.info(f'Module {module.name!r} dropped')
  181. def __del__(self, *args, **kwargs):
  182. if self.name is not None and self.name in type(self).__modulesByName:
  183. logger.info(f'Module {self.name!r} is being destroyed, dropping')
  184. del type(self).__modulesByName[self.name]
  185. # type has no __del__ method, no need to call it.
  186. class Module(metaclass = ModuleMeta):
  187. '''An abstract base class for a module.'''
  188. name: typing.Optional[str] = None
  189. '''The name of the module. Modules without a name are ignored. Names must be unique and may only contain a-z, underscores, and hyphens.'''
  190. @staticmethod
  191. def matches(inputUrl: InputURL) -> bool:
  192. '''Whether or not this module is for handling `inputUrl`.'''
  193. return False
  194. def __init__(self, inputUrl: InputURL, id_: typing.Optional[str] = None):
  195. self._inputUrl = inputUrl
  196. self._url = inputUrl.url
  197. self._id = id_
  198. self._httpClient = HttpClient()
  199. @abc.abstractmethod
  200. def process(self) -> Result:
  201. '''Perform the relevant retrieval(s)'''
  202. def __repr__(self):
  203. return f'{type(self).__module__}.{type(self).__name__}({self._inputUrl!r})'
  204. def get_module_class(inputUrl: InputURL) -> typing.Type[Module]:
  205. '''Get the Module class most suitable for handling `inputUrl`.'''
  206. # Ensure that modules are imported
  207. # This can't be done at the top because the modules need to refer back to the Module class.
  208. import codearchiver.modules
  209. # Check if the URL references one of the modules directly
  210. if inputUrl.moduleScheme:
  211. if module := ModuleMeta.get_module_by_name(inputUrl.moduleScheme):
  212. logger.info(f'Selecting module {module.__module__}.{module.__name__}')
  213. return module
  214. else:
  215. raise RuntimeError(f'No module with name {inputUrl.moduleScheme!r} exists')
  216. # Check if exactly one of the modules matches
  217. matches = [class_ for class_ in ModuleMeta.iter_modules() if class_.matches(inputUrl)]
  218. if len(matches) >= 2:
  219. logger.error('Multiple matching modules for input URL')
  220. logger.debug(f'Matching modules: {matches!r}')
  221. raise RuntimeError('Multiple matching modules for input URL')
  222. if matches:
  223. logger.info(f'Selecting module {matches[0].__module__}.{matches[0].__name__}')
  224. return matches[0]
  225. raise RuntimeError('No matching modules for input URL')
  226. def get_module_instance(inputUrl: InputURL, **kwargs) -> Module:
  227. '''Get an instance of the Module class most suitable for handling `inputUrl`.'''
  228. return get_module_class(inputUrl)(inputUrl, **kwargs)