Respawn ticket use working

This commit is contained in:
SimplifiedPrivacy 2026-10-26 18:45:01 -04:00
parent f53661fc60
commit 958c906f30
8 changed files with 153 additions and 29 deletions

View file

@ -38,7 +38,7 @@ def prepare_tickets(
ticket_observer: TicketObserver, ticket_observer: TicketObserver,
connection_observer: ConnectionObserver, connection_observer: ConnectionObserver,
which_ticket: Optional[int] = None, which_ticket: Optional[int] = None,
billing_code: Optional[int] = None billing_code: Optional[str] = None
) -> Result: ) -> Result:
logger.info("prepare_tickets has begun") logger.info("prepare_tickets has begun")

View file

@ -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." 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) 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: else:
error_stack = get_traceback_line(error) 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: def strip_filename(path: str) -> str:
"""Returns only the filename from a full system path.""" """Returns only the filename from a full system path."""

View file

@ -39,6 +39,8 @@ class ThreadPlumbing:
if not task: if not task:
# 1. Create the partial immediately in the main thread # 1. Create the partial immediately in the main thread
task = partial(self.action, *self.args, **self.kwargs) 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 # 2. Define a simple wrapper to run the task and then handle the result
def wrapper(): def wrapper():
@ -63,21 +65,44 @@ class ThreadPlumbing:
"""Get a potential function prescription and return it to the main thread.""" """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: if not result.function_choice:
result.function_choice = resolve_prescription(result, self.ENUM_MAP, *self.args, **self.kwargs) result.function_choice = resolve_prescription(result, self.ENUM_MAP, *self.args, **self.kwargs)
logger.info(f"result.function_choice is {result.function_choice}") logger.info(f"result.function_choice is {result.function_choice}")
else: else:
logger.info("Using the pre-existing function choice for this error.") 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 # 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) 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): def _back_on_main_thread(self, result: Result):
"""Decide: retry, show popup, or final callback""" """Decide: retry, show popup, or final callback"""
@ -183,13 +208,48 @@ def normalize_seq(s):
return tuple(s) if s is not None else () 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): def resolve_prescription(result: Result, ENUM_MAP: dict, *args, **kwargs):
""" """
Find the correct solution to the type of enum problem, Find the correct solution to the type of enum problem,
And then add the args from either the original caller's args, And then add the args from either the original caller's args,
or the defaults for that error type 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. # Priority 1: If the function explicitly provided a full partial, use it.
if result.function_choice: if result.function_choice:
@ -207,6 +267,7 @@ def resolve_prescription(result: Result, ENUM_MAP: dict, *args, **kwargs):
# Handle the None case (no solution) # Handle the None case (no solution)
if enum_value is None: if enum_value is None:
logger.info("No enum")
return None return None
# Unpack the enum value - could be just a function or (function, default_args) # 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. # requires nothing, we're done, return it.
if not function_requirements: if not function_requirements:
logger.info("Function requires nothing, we return as is..")
return func return func
# Priority 3: Does it want the result itself? # 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 # Priority 4: Use original args/kwargs
try: try:
bound = sig.bind(*args, **kwargs) logger.info("Attempting to use the filtered original args and kwargs")
bound.apply_defaults() final_args = try_original_args_kwargs(sig, args, kwargs)
return partial(func, **bound.arguments) logger.info("Using the filtered original args and kwargs")
return partial(func, **final_args)
except TypeError: except TypeError:
logger.info("Original args & kwargs are missing data or have wrong types")
pass # Not enough, move to priority 4 pass # Not enough, move to priority 4
# Priority 5: Use original args/kwargs PLUS defaults # 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 = sig.bind(**final_kwargs)
bound.apply_defaults() bound.apply_defaults()
logger.info("Applying both original with defaults..")
return partial(func, **bound.arguments) return partial(func, **bound.arguments)
except TypeError: except TypeError:
pass 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 return False # Still args or kwargs lacking

View file

@ -59,6 +59,7 @@ class ResultError(Enum):
PORT = "port" PORT = "port"
RENEGOTIATION = "renegotiation" RENEGOTIATION = "renegotiation"
ATTEMPTS = "attempts" ATTEMPTS = "attempts"
RECONNECT = "reconnect"
NAVIGATE_TO = "navigate_to" NAVIGATE_TO = "navigate_to"
UNKNOWN = "unknown" UNKNOWN = "unknown"
@ -74,6 +75,7 @@ class Result():
backoff_strategy: Optional[BackoffStrategy] = None backoff_strategy: Optional[BackoffStrategy] = None
function_choice: Optional[partial] = None function_choice: Optional[partial] = None
no_option: Optional[partial] = None no_option: Optional[partial] = None
double_dip: bool = False
navigate_to: Optional[str] = None navigate_to: Optional[str] = None
# def user_message(self) -> str: # def user_message(self) -> str:

View file

@ -75,6 +75,18 @@ def format_server_response(api_response: ApiResponse|dict, desired_type: str) ->
def translate_server_failure(server_reply: ServerReply) -> Result: def translate_server_failure(server_reply: ServerReply) -> Result:
"""Translate the server's failure to the UI""" """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}") 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] client_error = TRANSLATION_DICT[server_reply.error_type]
return Result(valid=False, error_type=client_error, message=server_reply.message) return Result(valid=False, error_type=client_error, message=server_reply.message)

View file

@ -40,13 +40,14 @@ class ServerReply():
boolean_result: Optional[bool] = None boolean_result: Optional[bool] = None
conf: Optional[str] = None conf: Optional[str] = None
payment_status: Optional[bool] = None payment_status: Optional[bool] = None
billing_code: Optional[str] = None
expires_at: Optional[datetime] = field( expires_at: Optional[datetime] = field(
default=None, default=None,
metadata=config( metadata=config(
decoder=lambda x: datetime.fromisoformat(x.replace('Z', '+00:00')) if x else None decoder=lambda x: datetime.fromisoformat(x.replace('Z', '+00:00')) if x else None
) )
) )
location_id: Optional[int] = None
@dataclass_json @dataclass_json

View file

@ -82,7 +82,7 @@ def _try_with_permission_fallback(operation: Callable, interface: str) -> Result
def _hunt_and_kill(interface_name: str) -> Result: def _hunt_and_kill(interface_name: str) -> Result:
"""Finds all potential sing-box PIDs and kills them until the interface disappears.""" """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: if not id_results.valid:
return id_results return id_results
@ -109,6 +109,7 @@ def orchestrate_closing(current_state: Optional[SystemState], interface: str) ->
def try_state_pid(): def try_state_pid():
pid_res = get_process_id_from_state(current_state) pid_res = get_process_id_from_state(current_state)
if not pid_res.valid: if not pid_res.valid:
logger.info("Got pid from state json")
return pid_res return pid_res
return terminate_pid(pid_res.data) return terminate_pid(pid_res.data)
@ -116,11 +117,13 @@ def orchestrate_closing(current_state: Optional[SystemState], interface: str) ->
def try_exact_match(): def try_exact_match():
match = pid_tools.get_pid_by_app_name(exact_app_name=APP_NAME) match = pid_tools.get_pid_by_app_name(exact_app_name=APP_NAME)
if not match.valid: if not match.valid:
logger.info("Found a match")
return match return match
return terminate_pid(int(match.data)) return terminate_pid(int(match.data))
# Strategy 3: Hunt all related processes # Strategy 3: Hunt all related processes
def try_hunt(): def try_hunt():
logger.info("hunting and killing")
return _hunt_and_kill(interface) return _hunt_and_kill(interface)
strategies = [try_state_pid, try_exact_match, try_hunt] strategies = [try_state_pid, try_exact_match, try_hunt]

View file

@ -47,7 +47,8 @@ def save_ticket_use(
profile_id=profile_id, profile_id=profile_id,
billing_code=billing_code, billing_code=billing_code,
expires_at=expires_at, expires_at=expires_at,
which_ticket=which_ticket which_ticket=which_ticket,
billing_pending=False
) )
# update the ticket tracker: # 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") ticket_data = get_raw_string(str(which_ticket), "unblinded_final_ticket")
# key # key
which_key = TicketPaymentData().which_key() which_key = TicketPaymentData().which_key
if not 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?") 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, which_ticket: int,
ticket_observer: TicketObserver, ticket_observer: TicketObserver,
connection_observer: ConnectionObserver, connection_observer: ConnectionObserver,
connect_after: bool = False
) -> Result: ) -> Result:
################################### ###################################
@ -144,7 +146,7 @@ def use_ticket_orchestrator(
################################### ###################################
# PREP PAYLOAD # 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: if not payload_result.valid:
return payload_result return payload_result
payload = payload_result.data payload = payload_result.data
@ -171,28 +173,60 @@ def use_ticket_orchestrator(
ticket_observer.notify("error", subject=server_reply.message) ticket_observer.notify("error", subject=server_reply.message)
return server_reply 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 # SUCCESS
################################### ###################################
if server_reply.valid or server_reply.error_type == ServerError.ALREADY_USED: billing_code = server_reply.billing_code
billing_code = server_reply.billing_code expires_at = server_reply.expires_at
expires_at = server_reply.expires_at
if not billing_code or not expires_at: # FILTER:
return Result(valid=False, error_type=ResultError.SERVER_SIDE, message="Server Replied it worked, but failed to provide a valid code.") 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:
profile_id=profile_id, saved = save_ticket_use(
billing_code=billing_code, profile_id=profile_id,
expires_at=expires_at, billing_code=billing_code,
location_id=location_id, expires_at=expires_at,
which_ticket=which_ticket 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 # EXPIRED
################################### ###################################
if server_reply.error_type == ServerError.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." 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) return Result(valid=False, error_type=ResultError.TICKET_EXPIRED, message=error_msg)
@ -207,6 +241,8 @@ def use_ticket_orchestrator(
# NODE DOWN # NODE DOWN
################################### ###################################
if server_reply.error_type == ServerError.NODE_ERROR: 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?" 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. return Result(valid=False, error_type=ResultError.NODE_ERROR, message=error_msg) # Each GUI will navigate to edit.