Respawn ticket use working
This commit is contained in:
parent
f53661fc60
commit
958c906f30
8 changed files with 153 additions and 29 deletions
|
|
@ -38,7 +38,7 @@ def prepare_tickets(
|
|||
ticket_observer: TicketObserver,
|
||||
connection_observer: ConnectionObserver,
|
||||
which_ticket: Optional[int] = None,
|
||||
billing_code: Optional[int] = None
|
||||
billing_code: Optional[str] = None
|
||||
) -> Result:
|
||||
|
||||
logger.info("prepare_tickets has begun")
|
||||
|
|
|
|||
|
|
@ -65,9 +65,13 @@ def translate_error(error: Type[Exception], profile_id: int) -> Result:
|
|||
error_msg = f"You're missing the {name_of_package} package. Please install it."
|
||||
return Result(valid=False, error_type=ResultError.MISSING_SOFTWARE, message=error_msg)
|
||||
|
||||
if isinstance(error, FileNotFoundError):
|
||||
error_string = str(error)
|
||||
return Result(valid=False, error_type=ResultError.FILE_SYSTEM, message=error_string)
|
||||
|
||||
else:
|
||||
error_stack = get_traceback_line(error)
|
||||
return Result(valid=False, error_type=ResultError.UNKNOWN, message=error_stack.message_for_user)
|
||||
return Result(valid=False, error_stack=error_stack, error_type=ResultError.UNKNOWN, message=error_stack.message_for_user)
|
||||
|
||||
def strip_filename(path: str) -> str:
|
||||
"""Returns only the filename from a full system path."""
|
||||
|
|
|
|||
|
|
@ -39,6 +39,8 @@ class ThreadPlumbing:
|
|||
if not task:
|
||||
# 1. Create the partial immediately in the main thread
|
||||
task = partial(self.action, *self.args, **self.kwargs)
|
||||
else:
|
||||
logger.info(f"Using inserted task of {task}")
|
||||
|
||||
# 2. Define a simple wrapper to run the task and then handle the result
|
||||
def wrapper():
|
||||
|
|
@ -63,21 +65,44 @@ class ThreadPlumbing:
|
|||
"""Get a potential function prescription and return it to the main thread."""
|
||||
|
||||
#----------------------------
|
||||
# Function Prescription:
|
||||
# Went Right with a New Function Prescription to Run Right Now:
|
||||
#----------------------------
|
||||
if not result.valid:
|
||||
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)
|
||||
logger.info(f"double_dip_function is {double_dip_function}")
|
||||
if not double_dip_function or double_dip_function is not None:
|
||||
# self.kwargs.update(ui_caller=self.ui_caller)
|
||||
logger.info("Executing a double dip function.")
|
||||
self.execute(task=double_dip_function)
|
||||
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(f"result in plumbing background thread is {result}")
|
||||
self.ui_dispatcher.run_on_main_thread(self._back_on_main_thread, result)
|
||||
# print("ran on main thread")
|
||||
|
||||
def _back_on_main_thread(self, result: Result):
|
||||
"""Decide: retry, show popup, or final callback"""
|
||||
|
|
@ -183,13 +208,48 @@ def normalize_seq(s):
|
|||
return tuple(s) if s is not None else ()
|
||||
|
||||
|
||||
def try_original_args_kwargs(sig: inspect.Signature, input_args: tuple, input_kwargs: dict):
|
||||
|
||||
requirements = sig.parameters
|
||||
|
||||
# 1. Filter kwargs to remove any fields the function doesn't accept
|
||||
filtered_kwargs = {
|
||||
k: v for k, v in input_kwargs.items()
|
||||
if k in requirements
|
||||
}
|
||||
logger.info("Got the filtered kwargs")
|
||||
|
||||
# 2. Limit positional args to the number of parameters that can accept them
|
||||
positional_capable = [
|
||||
p for p in requirements.values()
|
||||
if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
|
||||
]
|
||||
filtered_args = input_args[:len(positional_capable)]
|
||||
logger.info("Got the limited positional capable")
|
||||
|
||||
# 3. Bind the filtered arguments (raises TypeError if required args are missing)
|
||||
bound = sig.bind(*filtered_args, **filtered_kwargs)
|
||||
bound.apply_defaults()
|
||||
logger.info("Bind worked.")
|
||||
|
||||
# 4. Manually check types based on function annotations
|
||||
for name, value in bound.arguments.items():
|
||||
param = requirements[name]
|
||||
if param.annotation is not inspect.Parameter.empty:
|
||||
if not isinstance(value, param.annotation):
|
||||
raise TypeError(f"Argument '{name}' expected {param.annotation}, got {type(value)}")
|
||||
logger.info("Type check worked. returning..")
|
||||
|
||||
return bound.arguments
|
||||
|
||||
|
||||
def resolve_prescription(result: Result, ENUM_MAP: dict, *args, **kwargs):
|
||||
"""
|
||||
Find the correct solution to the type of enum problem,
|
||||
And then add the args from either the original caller's args,
|
||||
or the defaults for that error type
|
||||
"""
|
||||
logger.info(f"resolve_prescription is being called for {result}.")
|
||||
logger.info(f"resolve_prescription is being called for {result} with *args, **kwargs of {args} {kwargs}")
|
||||
|
||||
# Priority 1: If the function explicitly provided a full partial, use it.
|
||||
if result.function_choice:
|
||||
|
|
@ -207,6 +267,7 @@ def resolve_prescription(result: Result, ENUM_MAP: dict, *args, **kwargs):
|
|||
|
||||
# Handle the None case (no solution)
|
||||
if enum_value is None:
|
||||
logger.info("No enum")
|
||||
return None
|
||||
|
||||
# Unpack the enum value - could be just a function or (function, default_args)
|
||||
|
|
@ -222,6 +283,7 @@ def resolve_prescription(result: Result, ENUM_MAP: dict, *args, **kwargs):
|
|||
|
||||
# requires nothing, we're done, return it.
|
||||
if not function_requirements:
|
||||
logger.info("Function requires nothing, we return as is..")
|
||||
return func
|
||||
|
||||
# Priority 3: Does it want the result itself?
|
||||
|
|
@ -249,10 +311,12 @@ def resolve_prescription(result: Result, ENUM_MAP: dict, *args, **kwargs):
|
|||
|
||||
# Priority 4: Use original args/kwargs
|
||||
try:
|
||||
bound = sig.bind(*args, **kwargs)
|
||||
bound.apply_defaults()
|
||||
return partial(func, **bound.arguments)
|
||||
logger.info("Attempting to use the filtered original args and kwargs")
|
||||
final_args = try_original_args_kwargs(sig, args, kwargs)
|
||||
logger.info("Using the filtered original args and kwargs")
|
||||
return partial(func, **final_args)
|
||||
except TypeError:
|
||||
logger.info("Original args & kwargs are missing data or have wrong types")
|
||||
pass # Not enough, move to priority 4
|
||||
|
||||
# Priority 5: Use original args/kwargs PLUS defaults
|
||||
|
|
@ -287,10 +351,12 @@ def resolve_prescription(result: Result, ENUM_MAP: dict, *args, **kwargs):
|
|||
bound = sig.bind(**final_kwargs)
|
||||
|
||||
bound.apply_defaults()
|
||||
logger.info("Applying both original with defaults..")
|
||||
return partial(func, **bound.arguments)
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
logger.error("We got a function, but failed to get the args/kwargs for it. Returning False")
|
||||
return False # Still args or kwargs lacking
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -59,6 +59,7 @@ class ResultError(Enum):
|
|||
PORT = "port"
|
||||
RENEGOTIATION = "renegotiation"
|
||||
ATTEMPTS = "attempts"
|
||||
RECONNECT = "reconnect"
|
||||
NAVIGATE_TO = "navigate_to"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
|
@ -74,6 +75,7 @@ class Result():
|
|||
backoff_strategy: Optional[BackoffStrategy] = None
|
||||
function_choice: Optional[partial] = None
|
||||
no_option: Optional[partial] = None
|
||||
double_dip: bool = False
|
||||
navigate_to: Optional[str] = None
|
||||
|
||||
# def user_message(self) -> str:
|
||||
|
|
|
|||
|
|
@ -75,6 +75,18 @@ def format_server_response(api_response: ApiResponse|dict, desired_type: str) ->
|
|||
|
||||
def translate_server_failure(server_reply: ServerReply) -> Result:
|
||||
"""Translate the server's failure to the UI"""
|
||||
|
||||
if not server_reply or not isinstance(server_reply, ServerReply):
|
||||
as_string = str(server_reply)
|
||||
return Result(valid=False, error_type=ServerReply.UNKNOWN, message=f"Empty/Blank server reply {as_string}")
|
||||
|
||||
if not server_reply.error_type:
|
||||
if server_reply.message:
|
||||
message = server_reply.message
|
||||
else:
|
||||
message = "There is no server reply message or error type."
|
||||
return Result(valid=False, error_type=ServerReply.UNKNOWN, message=message)
|
||||
|
||||
logger.error(f"Server-side failure occured. The server claims the reason is of type {server_reply.error_type} with {server_reply.message}")
|
||||
client_error = TRANSLATION_DICT[server_reply.error_type]
|
||||
return Result(valid=False, error_type=client_error, message=server_reply.message)
|
||||
|
|
|
|||
|
|
@ -40,13 +40,14 @@ class ServerReply():
|
|||
boolean_result: Optional[bool] = None
|
||||
conf: Optional[str] = None
|
||||
payment_status: Optional[bool] = None
|
||||
billing_code: Optional[str] = None
|
||||
expires_at: Optional[datetime] = field(
|
||||
default=None,
|
||||
metadata=config(
|
||||
decoder=lambda x: datetime.fromisoformat(x.replace('Z', '+00:00')) if x else None
|
||||
)
|
||||
)
|
||||
|
||||
location_id: Optional[int] = None
|
||||
|
||||
|
||||
@dataclass_json
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ def _try_with_permission_fallback(operation: Callable, interface: str) -> Result
|
|||
|
||||
def _hunt_and_kill(interface_name: str) -> Result:
|
||||
"""Finds all potential sing-box PIDs and kills them until the interface disappears."""
|
||||
id_results = pid_tools.get_pids_by_phrase(phase=APP_NAME)
|
||||
id_results = pid_tools.get_pids_by_phrase(APP_NAME)
|
||||
if not id_results.valid:
|
||||
return id_results
|
||||
|
||||
|
|
@ -109,6 +109,7 @@ def orchestrate_closing(current_state: Optional[SystemState], interface: str) ->
|
|||
def try_state_pid():
|
||||
pid_res = get_process_id_from_state(current_state)
|
||||
if not pid_res.valid:
|
||||
logger.info("Got pid from state json")
|
||||
return pid_res
|
||||
return terminate_pid(pid_res.data)
|
||||
|
||||
|
|
@ -116,11 +117,13 @@ def orchestrate_closing(current_state: Optional[SystemState], interface: str) ->
|
|||
def try_exact_match():
|
||||
match = pid_tools.get_pid_by_app_name(exact_app_name=APP_NAME)
|
||||
if not match.valid:
|
||||
logger.info("Found a match")
|
||||
return match
|
||||
return terminate_pid(int(match.data))
|
||||
|
||||
# Strategy 3: Hunt all related processes
|
||||
def try_hunt():
|
||||
logger.info("hunting and killing")
|
||||
return _hunt_and_kill(interface)
|
||||
|
||||
strategies = [try_state_pid, try_exact_match, try_hunt]
|
||||
|
|
|
|||
|
|
@ -47,7 +47,8 @@ def save_ticket_use(
|
|||
profile_id=profile_id,
|
||||
billing_code=billing_code,
|
||||
expires_at=expires_at,
|
||||
which_ticket=which_ticket
|
||||
which_ticket=which_ticket,
|
||||
billing_pending=False
|
||||
)
|
||||
|
||||
# update the ticket tracker:
|
||||
|
|
@ -79,7 +80,7 @@ def make_payload(which_ticket: int, which_location: int, protocol_choice: Protoc
|
|||
ticket_data = get_raw_string(str(which_ticket), "unblinded_final_ticket")
|
||||
|
||||
# key
|
||||
which_key = TicketPaymentData().which_key()
|
||||
which_key = TicketPaymentData().which_key
|
||||
if not which_key:
|
||||
return Result(valid=False, error_type=ResultError.MISSING_DATA, message="Which ticket billing key is missing from your config file. Did you wipe it?")
|
||||
|
||||
|
|
@ -99,6 +100,7 @@ def use_ticket_orchestrator(
|
|||
which_ticket: int,
|
||||
ticket_observer: TicketObserver,
|
||||
connection_observer: ConnectionObserver,
|
||||
connect_after: bool = False
|
||||
) -> Result:
|
||||
|
||||
###################################
|
||||
|
|
@ -144,7 +146,7 @@ def use_ticket_orchestrator(
|
|||
###################################
|
||||
# PREP PAYLOAD
|
||||
###################################
|
||||
payload_result = make_payload(which_ticket=which_ticket, protocol_choice=protocol_choice)
|
||||
payload_result = make_payload(which_ticket=which_ticket, protocol_choice=protocol_choice, which_location=location_id)
|
||||
if not payload_result.valid:
|
||||
return payload_result
|
||||
payload = payload_result.data
|
||||
|
|
@ -171,28 +173,60 @@ def use_ticket_orchestrator(
|
|||
ticket_observer.notify("error", subject=server_reply.message)
|
||||
return server_reply
|
||||
|
||||
|
||||
###################################
|
||||
# FAILURE
|
||||
###################################
|
||||
if not server_reply.valid:
|
||||
logger.info("Server's reply is invalid")
|
||||
if server_reply.error_type == ServerError.ALREADY_USED and server_reply.billing_code:
|
||||
logger.info("But it's because it's re-using a previously valid billing code. Continue..")
|
||||
else:
|
||||
logger.error("Returning a failure..")
|
||||
return return_ticket_failure(server_reply)
|
||||
|
||||
###################################
|
||||
# SUCCESS
|
||||
###################################
|
||||
if server_reply.valid or server_reply.error_type == ServerError.ALREADY_USED:
|
||||
billing_code = server_reply.billing_code
|
||||
expires_at = server_reply.expires_at
|
||||
|
||||
# FILTER:
|
||||
if not billing_code or not expires_at:
|
||||
return Result(valid=False, error_type=ResultError.SERVER_SIDE, message="Server Replied it worked, but failed to provide a valid code.")
|
||||
|
||||
return save_ticket_use(
|
||||
# SAVE:
|
||||
saved = save_ticket_use(
|
||||
profile_id=profile_id,
|
||||
billing_code=billing_code,
|
||||
expires_at=expires_at,
|
||||
location_id=location_id,
|
||||
which_ticket=which_ticket
|
||||
)
|
||||
# save failed:
|
||||
if not saved.valid:
|
||||
logger.error("Failed to Save")
|
||||
return saved
|
||||
|
||||
# not using it now:
|
||||
if not connect_after:
|
||||
return saved
|
||||
|
||||
# using it now:
|
||||
logger.info("Submitting to reconnect..")
|
||||
return Result(valid=True, double_dip=True, error_type=ResultError.RECONNECT)
|
||||
|
||||
|
||||
def return_ticket_failure(server_reply: ServerReply) -> Result:
|
||||
notification = "Ticket Use Failed."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
|
||||
###################################
|
||||
# EXPIRED
|
||||
###################################
|
||||
if server_reply.error_type == ServerError.EXPIRED:
|
||||
notification = "Ticket is Expired."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
error_msg = "This ticket is expired. Do you want to wipe ALL your tickets? To start over."
|
||||
return Result(valid=False, error_type=ResultError.TICKET_EXPIRED, message=error_msg)
|
||||
|
||||
|
|
@ -207,6 +241,8 @@ def use_ticket_orchestrator(
|
|||
# NODE DOWN
|
||||
###################################
|
||||
if server_reply.error_type == ServerError.NODE_ERROR:
|
||||
notification = "Error with that Location/Node."
|
||||
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||
error_msg = f"{server_reply.message}. Do you want to switch locations for this profile?"
|
||||
return Result(valid=False, error_type=ResultError.NODE_ERROR, message=error_msg) # Each GUI will navigate to edit.
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue