| 1 | # Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | # All rights reserved. |
| 3 | # |
| 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | # the root directory of this source tree. |
| 6 | |
| 7 | import asyncio |
| 8 | |
| 9 | from typing import List, Optional |
| 10 | |
| 11 | import fire |
| 12 | import httpx |
| 13 | from termcolor import cprint |
| 14 | |
| 15 | from .shields import * # noqa: F403 |
| 16 | |
| 17 | |
| 18 | class ShieldsClient(Shields): |
| 19 | def __init__(self, base_url: str): |
| 20 | self.base_url = base_url |
| 21 | |
| 22 | async def initialize(self) -> None: |
| 23 | pass |
| 24 | |
| 25 | async def shutdown(self) -> None: |
| 26 | pass |
| 27 | |
| 28 | async def list_shields(self) -> List[ShieldSpec]: |
| 29 | async with httpx.AsyncClient() as client: |
| 30 | response = await client.get( |
| 31 | f"{self.base_url}/shields/list", |
| 32 | headers={"Content-Type": "application/json"}, |
| 33 | ) |
| 34 | response.raise_for_status() |
| 35 | return [ShieldSpec(**x) for x in response.json()] |
| 36 | |
| 37 | async def get_shield(self, shield_type: str) -> Optional[ShieldSpec]: |
| 38 | async with httpx.AsyncClient() as client: |
| 39 | response = await client.get( |
| 40 | f"{self.base_url}/shields/get", |
| 41 | params={ |
| 42 | "shield_type": shield_type, |
| 43 | }, |
| 44 | headers={"Content-Type": "application/json"}, |
| 45 | ) |
| 46 | response.raise_for_status() |
| 47 | |
| 48 | j = response.json() |
| 49 | if j is None: |
| 50 | return None |
| 51 | |
| 52 | return ShieldSpec(**j) |
| 53 | |
| 54 | |
| 55 | async def run_main(host: str, port: int, stream: bool): |
| 56 | client = ShieldsClient(f"http://{host}:{port}") |
| 57 | |
| 58 | response = await client.list_shields() |
| 59 | cprint(f"list_shields response={response}", "green") |
| 60 | |
| 61 | |
| 62 | def main(host: str, port: int, stream: bool = True): |
| 63 | asyncio.run(run_main(host, port, stream)) |
| 64 | |
| 65 | |
| 66 | if __name__ == "__main__": |
| 67 | fire.Fire(main) |