Skip to content

Gracefully handle trying to connect to a UNIX socket on Windows #617

Closed

Description

@michaeloliverx

Running this code on a Windows machine:

import httpcore

http = httpcore.ConnectionPool(uds="/var/run/docker.sock")
response = http.request("GET", "http://docker/info")

Results in the following:

Traceback (most recent call last):
  File <omitted>\fix-unix-socket.py", line 4, in <module>
    response = http.request("GET", "http://docker/info")
  File <omitted>\httpcore\_sync\interfaces.py", line 43, in request
    response = self.handle_request(request)
  File <omitted>\httpcore\_sync\connection_pool.py", line 252, in handle_request
    raise exc
  File <omitted>\httpcore\_sync\connection_pool.py", line 236, in handle_request
    response = connection.handle_request(request)
  File <omitted>\httpcore\_sync\connection.py", line 86, in handle_request      
    raise exc
  File <omitted>\httpcore\_sync\connection.py", line 63, in handle_request      
    stream = self._connect(request)
  File <omitted>\httpcore\_sync\connection.py", line 121, in _connect
    stream = self._network_backend.connect_unix_socket(
  File <omitted>\httpcore\backends\sync.py", line 106, in connect_unix_socket   
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
AttributeError: module 'socket' has no attribute 'AF_UNIX'

Do we want to handle it here?

def connect_unix_socket(
self, path: str, timeout: typing.Optional[float] = None
) -> NetworkStream: # pragma: nocover
exc_map: ExceptionMapping = {
socket.timeout: ConnectTimeout,
OSError: ConnectError,
}
with map_exceptions(exc_map):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect(path)
return SyncStream(sock)

    def connect_unix_socket(
        self, path: str, timeout: typing.Optional[float] = None
    ) -> NetworkStream:  # pragma: nocover
        if sys.platform == "win32":
            raise RuntimeError("Cannot connect to UNIX socket on a non UNIX system")
            
        exc_map: ExceptionMapping = {
            socket.timeout: ConnectTimeout,
            OSError: ConnectError,
        }
        with map_exceptions(exc_map):
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            sock.settimeout(timeout)
            sock.connect(path)
        return SyncStream(sock)

Activity

  1. lovelydinosaur commented on Nov 21, 2022

    @lovelydinosaur
    Member

    Seems like a good idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions