ruạṛ
import builtins import logging import time import requests from app.config import get_cbs_endpoint from app.utils.request_context import cbs_callback_uuid_context, cbs_custom_callback_url_context from app.utils.utility_functions import LogPrinter # Enable logging if not run as CLI if __name__ != "__main__": LogPrinter.enable_logging() def logger_print(*args, **kwargs): message = " ".join(str(arg) for arg in args) logger = logging.getLogger("bart") logger.info(message) def is_running_as_cli(): return __name__ == "__main__" if not is_running_as_cli(): builtins.print = logger_print MAX_RETRIES = 3 RETRY_BACKOFF_SECONDS = 2 # base backoff time in seconds # Function to handle the callback to CBS after the job is done def call_cbs_callback(cbs_job_id, action_name, action_status, action_data): callback_url = f"{get_cbs_endpoint()}/v1/cbs/callback" if cbs_custom_callback_url_context.get(): callback_url = f"{cbs_custom_callback_url_context.get()}/v1/cbs/callback" payload = { "job_id": int(cbs_job_id), "data": { "action_name": action_name, "action_status": action_status, "action_data": action_data } } uuid_secret = cbs_callback_uuid_context.get() if not uuid_secret: LogPrinter.error("UUID not found in request context") return headers = { "X-CBS-Platform": "bart", "X-CBS-Brand": "bart", "X-CBS-Secret-Key": f"{cbs_job_id}:{uuid_secret}" } for attempt in range(1, MAX_RETRIES + 1): try: LogPrinter.info(f"Callback to CBS (Attempt {attempt}): {payload}") response = requests.post(callback_url, json=payload, headers=headers) LogPrinter.info(f"Response from CBS: {response.status_code} - {response.text.strip()}") response.raise_for_status() return # Exit if successful except requests.RequestException as e: LogPrinter.warn(f"Attempt {attempt} failed to call CBS callback: {e}") if attempt < MAX_RETRIES: sleep_time = RETRY_BACKOFF_SECONDS ** attempt LogPrinter.info(f"Retrying after {sleep_time} seconds...") time.sleep(sleep_time) else: LogPrinter.error("All retries to CBS callback failed.")
cải xoăn