|
| 1 | +"""CubeJS client.""" |
| 2 | + |
| 3 | +import httpx |
| 4 | +import tenacity |
| 5 | +from loguru import logger |
| 6 | + |
| 7 | +from cubejs.errors import ( |
| 8 | + AuthorizationError, |
| 9 | + ContinueWaitError, |
| 10 | + RequestError, |
| 11 | + ServerError, |
| 12 | + UnexpectedResponseError, |
| 13 | +) |
| 14 | +from cubejs.model import CubeJSAuth, CubeJSRequest, CubeJSResponse |
| 15 | + |
| 16 | + |
| 17 | +def _error_handler(response: httpx.Response) -> None: |
| 18 | + """Handle errors from CubeJS server. |
| 19 | +
|
| 20 | + According to CubeJS docs the expected responses are: |
| 21 | + 200 - success |
| 22 | + 400 - request error |
| 23 | + 403 - authorization error |
| 24 | + 500 - server error |
| 25 | +
|
| 26 | + Anything other than 200 is unexpected and will raise an error. |
| 27 | +
|
| 28 | + """ |
| 29 | + if response.status_code == 403: |
| 30 | + raise AuthorizationError(response.text) |
| 31 | + if response.status_code == 400: |
| 32 | + raise RequestError(response.text) |
| 33 | + if "Continue wait" in response.text: |
| 34 | + raise ContinueWaitError() |
| 35 | + if response.status_code == 500: |
| 36 | + raise ServerError(response.text) |
| 37 | + if response.status_code != 200: |
| 38 | + raise UnexpectedResponseError(response.text) |
| 39 | + |
| 40 | + |
| 41 | +@tenacity.retry( |
| 42 | + retry=tenacity.retry_if_exception_type(ContinueWaitError), |
| 43 | + wait=tenacity.wait_exponential(multiplier=2, min=1, max=30), |
| 44 | + stop=tenacity.stop_after_attempt(5), |
| 45 | +) |
| 46 | +async def get_measures(auth: CubeJSAuth, request: CubeJSRequest) -> CubeJSResponse: |
| 47 | + """Get measures from cubejs. |
| 48 | +
|
| 49 | + Args: |
| 50 | + auth: cubejs auth. |
| 51 | + request: definition of measures you want to fetch from the semantic layer. |
| 52 | +
|
| 53 | + Returns: |
| 54 | + cubejs response with requested measures. |
| 55 | +
|
| 56 | + Raises: |
| 57 | + AuthorizationError: if the request is not authorized. |
| 58 | + RequestError: if the request is invalid. |
| 59 | + ContinueWaitError: if the request is not ready yet. |
| 60 | + ServerError: if the server is not available. |
| 61 | + UnexpectedResponseError: if the response is unexpected. |
| 62 | +
|
| 63 | + """ |
| 64 | + logger.debug(f"Getting measures from {auth.host}") |
| 65 | + url = f"{auth.host}/cubejs-api/v1/load" |
| 66 | + headers = {"Authorization": auth.token} |
| 67 | + request_payload = {"query": request.model_dump(by_alias=True, exclude_none=True)} |
| 68 | + logger.debug(f"Query payload: {request_payload}") |
| 69 | + async with httpx.AsyncClient(timeout=60) as client: |
| 70 | + response = await client.post(url=url, json=request_payload, headers=headers) |
| 71 | + _error_handler(response) |
| 72 | + cube_js_response = CubeJSResponse(**response.json()) |
| 73 | + logger.debug("CubeJS response succesfully received!") |
| 74 | + return cube_js_response |
0 commit comments