|
| 1 | +from typing import Literal |
| 2 | + |
| 3 | +from netunicorn.base import Task |
| 4 | +from netunicorn.base.types import FlagValues |
| 5 | + |
| 6 | + |
| 7 | +class SetFlagTask(Task): |
| 8 | + def __init__(self, flag_name: str, flag_values: FlagValues, *args, **kwargs): |
| 9 | + if flag_values.int_value is None and flag_values.text_value is None: |
| 10 | + raise ValueError("Either int_value or text_value must be set") |
| 11 | + |
| 12 | + self.flag_name = flag_name |
| 13 | + self.flag_values = flag_values |
| 14 | + super().__init__(*args, **kwargs) |
| 15 | + |
| 16 | + def run(self) -> None: |
| 17 | + import requests as req |
| 18 | + import os |
| 19 | + |
| 20 | + gateway = os.environ["NETUNICORN_GATEWAY_ENDPOINT"] |
| 21 | + experiment_id = os.environ["NETUNICORN_EXPERIMENT_ID"] |
| 22 | + |
| 23 | + req.post( |
| 24 | + f"{gateway}/api/v1/experiment/{experiment_id}/flag/{self.flag_name}", |
| 25 | + json=self.flag_values.dict(), |
| 26 | + ).raise_for_status() |
| 27 | + |
| 28 | + |
| 29 | +class GetFlagTask(Task): |
| 30 | + def __init__(self, flag_name: str, *args, **kwargs): |
| 31 | + self.flag_name = flag_name |
| 32 | + super().__init__(*args, **kwargs) |
| 33 | + |
| 34 | + def run(self) -> FlagValues: |
| 35 | + import requests as req |
| 36 | + import os |
| 37 | + |
| 38 | + gateway = os.environ["NETUNICORN_GATEWAY_ENDPOINT"] |
| 39 | + experiment_id = os.environ["NETUNICORN_EXPERIMENT_ID"] |
| 40 | + |
| 41 | + result = req.get( |
| 42 | + f"{gateway}/api/v1/experiment/{experiment_id}/flag/{self.flag_name}" |
| 43 | + ).json() |
| 44 | + return FlagValues(**result) |
| 45 | + |
| 46 | + |
| 47 | +class _AtomicOperationFlagTask(Task): |
| 48 | + def __init__(self, flag_name: str, operation: Literal['increment', 'decrement'], *args, **kwargs): |
| 49 | + self.flag_name = flag_name |
| 50 | + self.operation = operation |
| 51 | + super().__init__(*args, **kwargs) |
| 52 | + |
| 53 | + def run(self) -> None: |
| 54 | + import requests as req |
| 55 | + import os |
| 56 | + |
| 57 | + gateway = os.environ["NETUNICORN_GATEWAY_ENDPOINT"] |
| 58 | + experiment_id = os.environ["NETUNICORN_EXPERIMENT_ID"] |
| 59 | + |
| 60 | + req.post( |
| 61 | + f"{gateway}/api/v1/experiment/{experiment_id}/flag/{self.flag_name}/{self.operation}", |
| 62 | + ).raise_for_status() |
| 63 | + |
| 64 | + |
| 65 | +class AtomicIncrementFlagTask(_AtomicOperationFlagTask): |
| 66 | + def __init__(self, flag_name: str, *args, **kwargs): |
| 67 | + super().__init__(flag_name, 'increment', *args, **kwargs) |
| 68 | + |
| 69 | + |
| 70 | +class AtomicDecrementFlagTask(_AtomicOperationFlagTask): |
| 71 | + def __init__(self, flag_name: str, *args, **kwargs): |
| 72 | + super().__init__(flag_name, 'decrement', *args, **kwargs) |
0 commit comments