-
-
Notifications
You must be signed in to change notification settings - Fork 260
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor HID write timeout logic (#1621)
Related #1026 This PR moves the multiprocessing timeout logic to a separate `execute` module, along with other related classes. This change simplifies the `hid.write` module by stripping out multiprocessing details not directly related to writing to the HID interface. ### Notes 1. We've moved the following classes to the new `execute` module: * `ProcessWithResult` * `ProcessResult` 1. We've moved the HID write timeout logic to a generic `execute.with_timeout` function 2. We've moved `hid.write_test.py` to `execute_test.py` 3. I'm not really sure why we need this function or if it is still required, but I kept it around anyway: https://github.com/tiny-pilot/tinypilot/blob/106e6448bd931da40f9e49c5fc97d5970fffa6d6/app/process.py#L84-L87 ### Peer testing You can test this build by running the following command on a device: ```bash curl \ --silent \ --show-error \ --location \ https://raw.githubusercontent.com/tiny-pilot/tinypilot/master/scripts/install-bundle | \ sudo bash -s -- \ https://output.circle-artifacts.com/output/job/5789b04e-8216-42fe-ad1e-227948464d03/artifacts/0/bundler/dist/tinypilot-community-20230907T1543Z-1.9.1-12+e1ba857.tgz ``` <a data-ca-tag href="https://codeapprove.com/pr/tiny-pilot/tinypilot/1621"><img src="https://codeapprove.com/external/github-tag-allbg.png" alt="Review on CodeApprove" /></a>
- Loading branch information
1 parent
de10f0f
commit fb4b253
Showing
3 changed files
with
122 additions
and
79 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
import dataclasses | ||
import multiprocessing | ||
import typing | ||
|
||
|
||
@dataclasses.dataclass | ||
class ProcessResult: | ||
return_value: typing.Any = None | ||
exception: Exception = None | ||
|
||
def was_successful(self) -> bool: | ||
return self.exception is None | ||
|
||
|
||
class ProcessWithResult(multiprocessing.Process): | ||
"""A multiprocessing.Process object that keeps track of the child process' | ||
result (i.e., the return value and exception raised). | ||
Inspired by: | ||
https://stackoverflow.com/a/33599967/3769045 | ||
""" | ||
|
||
def __init__(self, *args, **kwargs): | ||
super().__init__(*args, **kwargs) | ||
# Create the Connection objects used for communication between the | ||
# parent and child processes. | ||
self.parent_conn, self.child_conn = multiprocessing.Pipe() | ||
|
||
def run(self): | ||
"""Method to be run in sub-process.""" | ||
result = ProcessResult() | ||
try: | ||
if self._target: | ||
result.return_value = self._target(*self._args, **self._kwargs) | ||
except Exception as e: | ||
result.exception = e | ||
raise | ||
finally: | ||
self.child_conn.send(result) | ||
|
||
def result(self): | ||
"""Get the result from the child process. | ||
Returns: | ||
If the child process has completed, a ProcessResult object. | ||
Otherwise, a None object. | ||
""" | ||
return self.parent_conn.recv() if self.parent_conn.poll() else None | ||
|
||
|
||
def with_timeout(function, *, args=None, timeout_in_seconds): | ||
"""Executes a function in a child process with a specified timeout. | ||
Usage example: | ||
with_timeout(save_contact, | ||
args=(first_name, last_name), | ||
timeout_in_seconds=0.5) | ||
Args: | ||
function: The function to be executed in a child process. | ||
args: Optional `function` arguments as a tuple. | ||
timeout_in_seconds: The execution time limit in seconds. | ||
Returns: | ||
The return value of the `function`. | ||
Raises: | ||
TimeoutError: If the execution time of the `function` exceeds the | ||
timeout `seconds`. | ||
""" | ||
process = ProcessWithResult(target=function, args=args or (), daemon=True) | ||
process.start() | ||
process.join(timeout=timeout_in_seconds) | ||
if process.is_alive(): | ||
process.kill() | ||
_wait_for_process_exit(process) | ||
result = process.result() | ||
if result is None: | ||
raise TimeoutError( | ||
f'Process failed to complete in {timeout_in_seconds} seconds') | ||
if not result.was_successful(): | ||
raise result.exception | ||
return result.return_value | ||
|
||
|
||
def _wait_for_process_exit(target_process): | ||
max_attempts = 3 | ||
for _ in range(max_attempts): | ||
target_process.join(timeout=0.1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters