|
| 1 | +import logging |
| 2 | +from typing import Any, Dict, List |
| 3 | + |
| 4 | +import config |
| 5 | +from api.services import http |
| 6 | + |
| 7 | + |
| 8 | +__all__ = ("get_runtimes", "get_runtimes_dict", "get_runtime", "Runtime") |
| 9 | + |
| 10 | +log = logging.getLogger() |
| 11 | + |
| 12 | +_base_url: str = ( |
| 13 | + config.piston_url().rstrip("/") + "/" |
| 14 | +) # make sure there's a / at the end |
| 15 | + |
| 16 | + |
| 17 | +async def _make_request(method: str, endpoint: str, data: Any = None) -> Any: |
| 18 | + async with http.session.request( |
| 19 | + method, |
| 20 | + _base_url + endpoint, |
| 21 | + json=data, |
| 22 | + raise_for_status=True, |
| 23 | + ) as response: |
| 24 | + return await response.json() |
| 25 | + |
| 26 | + |
| 27 | +async def get_runtimes() -> List["Runtime"]: |
| 28 | + """Get a list of all available runtimes.""" |
| 29 | + runtimes = await _make_request("GET", "runtimes") |
| 30 | + return [Runtime(runtime) for runtime in runtimes] |
| 31 | + |
| 32 | + |
| 33 | +async def get_runtimes_dict() -> Dict[str, List["Runtime"]]: |
| 34 | + """Get a dictionary of language names and aliases mapped to a list of |
| 35 | + all the runtimes with that name or alias. |
| 36 | + """ |
| 37 | + |
| 38 | + runtimes = await get_runtimes() |
| 39 | + runtimes_dict = {} |
| 40 | + |
| 41 | + for runtime in runtimes: |
| 42 | + if runtime.language in runtimes_dict: |
| 43 | + runtimes_dict[runtime.language].append(runtime) |
| 44 | + else: |
| 45 | + runtimes_dict[runtime.language] = [runtime] |
| 46 | + |
| 47 | + for alias in runtime.aliases: |
| 48 | + if alias in runtimes_dict: |
| 49 | + runtimes_dict[alias].append(runtime) |
| 50 | + else: |
| 51 | + runtimes_dict[alias] = [runtime] |
| 52 | + |
| 53 | + return runtimes_dict |
| 54 | + |
| 55 | + |
| 56 | +async def get_runtime(language: str) -> List["Runtime"]: |
| 57 | + """Get a runtime with a language or an alias.""" |
| 58 | + |
| 59 | + runtimes_dict = await get_runtimes_dict() |
| 60 | + return runtimes_dict.get(language, []) |
| 61 | + |
| 62 | + |
| 63 | +class Runtime: |
| 64 | + def __init__(self, data: dict): |
| 65 | + self.language = data["language"] |
| 66 | + self.version = data["version"] |
| 67 | + self.aliases = data["aliases"] |
| 68 | + self.runtime = data.get("runtime") |
0 commit comments