def validate_image(task: ExternalTask): """ To simulate BPMN/Failure/Success, this handler uses image name variable (to be passed when launching the process) """ log_context = { "WORKER_ID": task.get_worker_id(), "TASK_ID": task.get_task_id(), "TOPIC": task.get_topic_name() } log_with_context("executing validate_image", log_context) img_name = task.get_variable('imgName') if "poor" in img_name: return task.bpmn_error( "POOR_QUALITY_IMAGE", "Image quality is bad", { "img_rejection_code": "POOR_QUALITY_CODE_XX", "img_rejection_reason": f"Image quality must be at least GOOD" }) elif "jpg" in img_name: return task.complete({"img_approved": True}) elif "corrupt" in img_name: return task.failure("Cannot validate image", "image is corrupted", 0, default_config.get("retryTimeout")) else: return task.bpmn_error( "INVALID_IMAGE", "Image extension must be jpg", { "img_rejection_code": "INVALID_IMG_NAME", "img_rejection_reason": f"Image name {img_name} is invalid" })
def generic_task_handler(task: ExternalTask): log_context = {"WORKER_ID": task.get_worker_id(), "TASK_ID": task.get_task_id(), "TOPIC": task.get_topic_name()} log_with_context("executing generic task handler", log_context) return task.complete()
def fail_task_handler(task: ExternalTask): log_context = {"WORKER_ID": task.get_worker_id(), "TASK_ID": task.get_task_id(), "TOPIC": task.get_topic_name()} log_with_context("executing fail_task_handler", log_context) return task.failure("task failed", "task failed forced", 0, 10)
def _log_with_context(self, msg, topic=None, task_id=None, log_level='info', **kwargs): context = { "WORKER_ID": str(self.worker_id), "TOPIC": topic, "TASK_ID": task_id } log_with_context(msg, context=context, log_level=log_level, **kwargs)
def handle_task(task: ExternalTask): log_context = { "WORKER_ID": task.get_worker_id(), "TASK_ID": task.get_task_id(), "TOPIC": task.get_topic_name() } log_with_context( f"handle_task started: business key = {task.get_business_key()}", log_context) # simulate task execution execution_time = randint(0, 10) log_with_context( f"handle_task - business logic execution started for task: " f"it will execute for {execution_time} seconds", log_context) time.sleep(execution_time) # simulate that task results randomly into failure/BPMN error/complete failure = random_true() bpmn_error = False if failure else random_true() # override the values to simulate success/failure/BPMN error explicitly (if needed) failure, bpmn_error = False, False log_with_context( f"handle_task - business logic executed: failure: {failure}, bpmn_error: {bpmn_error}", log_context) return __handle_task_result(task, failure, bpmn_error)
def _log_with_context(self, msg, log_level='info', **kwargs): context = frozendict({"WORKER_ID": self.worker_id}) log_with_context(msg, context=context, log_level=log_level, **kwargs)