from core.infrastructure.plumbing_tools.resolve_prescription import resolve_prescription from core.infrastructure.plumbing_tools.result_chain import unwrap, audit from core.infrastructure.thread_dispatch import MainThreadDispatcher from core.infrastructure.error_popup import PopupProtocol, StackErrorProtocol from core.infrastructure.service_registry import ServiceLocator from core.errors.translate_error import get_traceback_line from core.models.Result import Result, ResultError from core.errors.logger import logger # generic: import threading from typing import Callable, Any, Optional, Type from functools import partial import sys MAX_ATTEMPTS = 2 class ThreadPlumbing: """ Manage Execution of functions on threads, and orchestrate their retries, then pass the data through to popup prompts for the user to decide how to solve any error, by enum type. """ def __init__(self, action: Callable, ui_dispatcher: MainThreadDispatcher, error_implementation: Type[PopupProtocol], stack_error_implementation: Type[StackErrorProtocol], ENUM_MAP: dict, auto_navigate_dict: dict, ui_caller: Optional[Callable] = None, *args, **kwargs): self.action = action self.ui_dispatcher = ui_dispatcher self.ui_caller = ui_caller self.error_implementation = error_implementation self.stack_error_implementation = stack_error_implementation self.ENUM_MAP = ENUM_MAP self.auto_navigate_dict = auto_navigate_dict self.navigator = ServiceLocator.get("navigator") self.args = args self.kwargs = kwargs self.attempt_count = 0 def execute(self, task = None): """Kicks off the action in a background thread""" # 0. If there's no task passed in, get it from the object initalization, if not task: # 1. Create the partial immediately in the main thread task = partial(self.action, *self.args, **self.kwargs) else: logger.info("Using inserted task") # 2. Define a simple wrapper to run the task and then handle the result def wrapper(): try: result = task() # Run the partial # logger.info(f"post complete result here is {result}") except Exception as e: error_msg = f"There was an error: {str(e)}" logger.error(error_msg) error_stack = get_traceback_line(e) error_msg = error_stack.message_for_user logger.error(error_msg) result = Result(valid=False, error_stack=error_stack, error_type=ResultError.UNKNOWN, message=error_msg) finally: # Process the result: self._on_complete(original_result=result) # 3. Spin up a single thread and start it thread = threading.Thread(target=wrapper, daemon=True) thread.start() def _on_complete(self, original_result: Result): """Get a potential function prescription and return it to the main thread.""" if not original_result: return if isinstance(original_result, Result): # Wrapper: if not original_result.valid: logger.error(audit(original_result)) result = unwrap(original_result) else: # Convert: result = convert_to_result(original_result) #---------------------------- # Went Right with a New Function Prescription to Run Right Now: #---------------------------- if result.valid and result.function_choice: logger.info("The result is a success, and the result provided a prescription to run immediately.") self.execute(result.function_choice) return #---------------------------- # DOUBLE DIP #---------------------------- elif result.double_dip: logger.info("Getting a double dip function.") double_dip_function = resolve_prescription(result, self.ENUM_MAP, *self.args, **self.kwargs) if double_dip_function is not None: # self.kwargs.update(ui_caller=self.ui_caller) logger.info("Executing a double dip function.") self.execute_already_on_background(task=double_dip_function) return else: logger.info(f"Result asked for a double dip, but there's no valid function to do so. double_dip_function is {double_dip_function}") #---------------------------- # Went Wrong? Diagnose Function Prescription: #---------------------------- elif not result.valid: if not result.function_choice: result.function_choice = resolve_prescription(result, self.ENUM_MAP, *self.args, **self.kwargs) logger.info(f"result.function_choice is {result.function_choice}") else: logger.info("Using the pre-existing function choice for this error.") else: logger.info("Result is valid, with no function needs. Just passing along to caller..") #---------------------------- # Back to main thread #---------------------------- logger.info("bringing back to main thread") self.ui_dispatcher.run_on_main_thread(self._back_on_main_thread, result) def _back_on_main_thread(self, result: Result): """Decide: retry, show popup, or final callback""" logger.info(result) #---------------------------- # OUTRIGHT ERROR STACK #---------------------------- if result.error_stack: error_window = self.stack_error_implementation(error_data=result.error_stack) user_choice = error_window.show_window() print(f"user_choice is {user_choice}") if user_choice == 2: sys.exit() return #---------------------------- # END ENTIRE PROGRAM #---------------------------- if result.error_type == ResultError.KILL_ENTIRE_APP: logger.info("Killing the entire app!") popup = self.error_implementation( choice=False, title="Restart the app", message=result.message, passed_result=result, end_app=True ) popup.show() #---------------------------- # NAVIGATE AWAY #---------------------------- # If the result sender explicitly asked us to navigate to a page with a ui callback, then bypass the popup: if result.error_type == ResultError.NAVIGATE_TO and self.ui_caller: logger.info("Plumbing was asked to NAVIGATE_TO so skipping to the ui_caller..") self.ui_caller(result) #---------------------------- # MAX TRIES #---------------------------- if result.valid or self.attempt_count >= MAX_ATTEMPTS: if self.ui_caller: logger.info("calling back with result due to max tries") if not result: result = Result(valid=False, error_type=ResultError.UNKNOWN, message="Plumbing is missing a result.") self.ui_caller(result) return #---------------------------- # SHOW CHOICE & POPUP #---------------------------- # do we need to decide on an action? choice = bool(result.function_choice) logger.info(f"Do we have to make a choice? {choice}") # if there's a message or a choice to make: if result.message or choice: # Then Show popup and wait for user choice popup = self.error_implementation( choice=bool(result.function_choice), title=f"Error: {result.error_type.value}", message=result.message, on_answer=self._on_popup_answer, passed_result=result, end_app=False ) # framework neutral show method logger.info("Showing a popup..") popup.show() logger.info("Showed the error popup.") #---------------------------- # COMPLETE #---------------------------- # otherwise return it as is: if self.ui_caller: logger.info("Returning from plumbing..") self.ui_caller(result) logger.error("No ui caller!!!") def _on_popup_answer(self, user_choice: bool, passed_result: Result): """User responded to popup""" #--------------------- # RUN THE CHOICE: #--------------------- if user_choice and passed_result.function_choice: self.attempt_count += 1 self.execute(passed_result.function_choice) else: #--------------------- # OR RUN THE "NO" CHOICE: #--------------------- # if the result originally prescribed it's own "no option": no_option = passed_result.no_option if no_option: self.execute(task=no_option) return #--------------------- # OR Just return back, #--------------------- # otherwise do the original UI call: if self.ui_caller: self.ui_caller(passed_result) def execute_already_on_background(self, task: Callable): """The other execute uses a thread, this lighter version assumes you're already on the background thread.""" try: result = task() except Exception as e: error_msg = f"There was an error: {str(e)}" logger.error(error_msg) error_stack = get_traceback_line(e) error_msg = error_stack.message_for_user logger.error(error_msg) result = Result(valid=False, error_stack=error_stack, error_type=ResultError.UNKNOWN, message=error_msg) finally: # Process the result: self._on_complete(original_result=result) # STANDALONE HELPERS: def convert_to_result(result: Any) -> Result: """Turn a non-Result object into a Result object""" error_msg = "Internal error where the result was returned in the wrong format." logger.error(error_msg) if isinstance(result, bool): if result: return Result(valid=True) else: return Result(valid=result, error_type=ResultError.INVALID_INPUT, message=error_msg) elif isinstance(result, dict): valid = result.get('valid', False) message = result.get('message', False) if valid: return Result(valid=True) if message: error_msg = message return Result(valid=valid, error_type=ResultError.INVALID_INPUT, message=error_msg) else: return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) # Optional Standalone Public API def take_plumbing_action(action: Callable, ui_dispatcher: MainThreadDispatcher, error_implementation: Type[PopupProtocol], ui_caller: Callable, *args, **kwargs): controller = ThreadPlumbing(action, ui_dispatcher, ui_caller, *args, **kwargs) controller.execute()