Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: extract _send_windows_request to the named_pipe_helper.py #32

Merged
merged 1 commit into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ def handle_request(self, data: str):
"""
request_dict = json.loads(data)
path = request_dict["path"]
body = json.loads(request_dict["body"])
body = None
if "body" in request_dict:
body = json.loads(request_dict["body"])
method = request_dict["method"]

if "params" in request_dict and request_dict["params"] != "null":
Expand Down
72 changes: 5 additions & 67 deletions src/openjd/adaptor_runtime/_background/frontend_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,7 @@
)

if OSName.is_windows():
import win32file
import win32pipe
import pywintypes
import winerror
from openjd.adaptor_runtime._background.named_pipe_helper import NamedPipeHelper
from openjd.adaptor_runtime._named_pipe.named_pipe_helper import NamedPipeHelper

_logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -236,11 +232,13 @@ def _send_request(
json_body: dict | None = None,
) -> http_client.HTTPResponse | Dict:
if OSName.is_windows():
return self._send_windows_request(
return NamedPipeHelper.send_named_pipe_request(
self.connection_settings.socket,
self._timeout_s,
method,
path,
json_body=json_body,
params=params if params else None,
json_body=json_body if json_body else None,
)
else:
return self._send_linux_request(
Expand Down Expand Up @@ -282,66 +280,6 @@ def _send_linux_request(

return response

def _send_windows_request(
self,
method: str,
path: str,
*,
params: dict | None = None,
json_body: dict | None = None,
) -> Dict:
start_time = time.time()
# Wait for the server pipe to become available.
handle = None
while handle is None:
try:
handle = win32file.CreateFile(
self.connection_settings.socket, # pipe name
# Give the read / write permission
win32file.GENERIC_READ | win32file.GENERIC_WRITE,
0, # Disable the sharing Mode
None, # TODO: Need to set the security descriptor. Right now, None means default security
win32file.OPEN_EXISTING, # Open existing pipe
0, # No Additional flags
None, # A valid handle to a template file, This parameter is ignored when opening an existing pipe.
)
except pywintypes.error as e:
# NamedPipe server may be not ready,
# or no additional resource to create new instance and need to wait for previous connection release
if e.args[0] in [winerror.ERROR_FILE_NOT_FOUND, winerror.ERROR_PIPE_BUSY]:
duration = time.time() - start_time
time.sleep(0.1)
# Check timeout limit
if duration > self._timeout_s:
_logger.error(
f"NamedPipe Server readiness timeout. Duration: {duration} seconds, "
f"Timeout limit: {self._timeout_s} seconds."
)
raise e
continue
_logger.error(f"Could not open pipe: {e}")
raise e

# Switch to message-read mode for the pipe. This ensures that each write operation is treated as a
# distinct message. For example, a single write operation like "Hello from client." will be read
# entirely in one request, avoiding partial reads like "Hello fr".
win32pipe.SetNamedPipeHandleState(handle, win32pipe.PIPE_READMODE_MESSAGE, None, None)

# Send a message to the server.
message_dict = {
"method": method,
"body": json.dumps(json_body),
"path": path,
}
if params:
message_dict["params"] = json.dumps(params)
message = json.dumps(message_dict)
NamedPipeHelper.write_to_pipe(handle, message)
_logger.debug(f"Message sent from frontend process: {message}")
result = NamedPipeHelper.read_from_pipe(handle)
handle.close()
return json.loads(result)

@property
def connection_settings(self) -> ConnectionSettings:
"""
Expand Down
99 changes: 0 additions & 99 deletions src/openjd/adaptor_runtime/_background/named_pipe_helper.py

This file was deleted.

4 changes: 2 additions & 2 deletions src/openjd/adaptor_runtime/_background/server_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ def __init__(
self,
server: Union[BackgroundHTTPServer, WinBackgroundNamedPipeServer],
response_fn: Callable,
body: Dict,
query_string_params: Dict[str, Any],
body: Dict | None = None,
query_string_params: Dict[str, Any] | None = None,
):
"""
Response generator
Expand Down
Loading