|
| 1 | +from typing import List |
| 2 | + |
| 3 | +import json |
| 4 | +import logging |
| 5 | + |
| 6 | +from hellpy import requests |
| 7 | +from hellpy.structures import ( |
| 8 | + BaseType, |
| 9 | + UrlBuilder, |
| 10 | + GetStatement, |
| 11 | + PutStatement, |
| 12 | + DelStatement, |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +class Store(object): |
| 17 | + """ |
| 18 | + Store is the main connector for HellDB from where all the |
| 19 | + reads and writes take place using an API designed to replicate |
| 20 | + the syntax of Latin, the query language developed for HellDB. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, port: int = 8080, host: str = '127.0.0.1'): |
| 24 | + |
| 25 | + """ Constructor for Store to build HellDB's url. """ |
| 26 | + |
| 27 | + self.url: str = f'http://{host}:{port}' |
| 28 | + self.url_store: UrlBuilder = UrlBuilder(self.url) |
| 29 | + |
| 30 | + if not self.ok(): |
| 31 | + logging.fatal(f"cannot connect to HellDB instance on {self.url}") |
| 32 | + |
| 33 | + @staticmethod |
| 34 | + def extract(resp_text: str) -> List[BaseType]: |
| 35 | + |
| 36 | + """ Helper method to return response's BaseType list generically. """ |
| 37 | + |
| 38 | + response = json.loads(resp_text) |
| 39 | + if len(response['errors']) != 0: |
| 40 | + logging.fatal('\n'.join(response['errors'])) |
| 41 | + else: |
| 42 | + return response['results'][0] |
| 43 | + |
| 44 | + def ok(self) -> bool: |
| 45 | + |
| 46 | + """ Checks whether HellDB is running healthy. """ |
| 47 | + |
| 48 | + resp = requests.get(self.url_store.status_url) |
| 49 | + return resp == "ok" |
| 50 | + |
| 51 | + def get(self, *keys: str) -> List[BaseType]: |
| 52 | + |
| 53 | + """ GET api for reading keys. """ |
| 54 | + |
| 55 | + get_statement = GetStatement(*keys) |
| 56 | + return Store.extract( |
| 57 | + requests.post( |
| 58 | + self.url_store.query_url, |
| 59 | + [get_statement], |
| 60 | + ), |
| 61 | + ) |
| 62 | + |
| 63 | + def delete(self, *keys: str) -> List[BaseType]: |
| 64 | + |
| 65 | + """ DEL api for deleting key value pairs. """ |
| 66 | + |
| 67 | + del_statement = DelStatement(*keys) |
| 68 | + return Store.extract( |
| 69 | + requests.post( |
| 70 | + self.url_store.query_url, |
| 71 | + [del_statement], |
| 72 | + ) |
| 73 | + ) |
| 74 | + |
| 75 | + def put(self, key: str, value: BaseType) -> List[BaseType]: |
| 76 | + |
| 77 | + """ PUT api for writing value to a key. """ |
| 78 | + |
| 79 | + put_statement = PutStatement(key, value) |
| 80 | + return Store.extract( |
| 81 | + requests.post( |
| 82 | + self.url_store.query_url, |
| 83 | + [put_statement], |
| 84 | + ) |
| 85 | + ) |
| 86 | + |
| 87 | + def __len__(self) -> int: |
| 88 | + |
| 89 | + """ Gets number of key-value pairs in HellDB. """ |
| 90 | + |
| 91 | + return int(requests.get(self.url_store.length_url)) |
0 commit comments