We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Groups cannot be listed using JSON IPC
Using the JSON serialization format in the IPC and trying to list groups yields exception 
```
Object of type set is not JSON serializable
NoneType: None
```
in the qtile logs and causes a `IPCError: Unable to decode json data` in the client end.

Reproduce with:
```python
from libqtile.command.client import (
    InteractiveCommandClient,
    Client,
    find_sockfile,
    IPCCommandInterface,
)
c = InteractiveCommandClient(
    command=IPCCommandInterface(
        Client(find_sockfile(), is_json=True)
    )
)
c.groups()
```



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `libqtile/ipc.py`
Content:
```
1 # Copyright (c) 2008, Aldo Cortesi. All rights reserved.
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a copy
4 # of this software and associated documentation files (the "Software"), to deal
5 # in the Software without restriction, including without limitation the rights
6 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 # copies of the Software, and to permit persons to whom the Software is
8 # furnished to do so, subject to the following conditions:
9 #
10 # The above copyright notice and this permission notice shall be included in
11 # all copies or substantial portions of the Software.
12 #
13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 # SOFTWARE.
20 
21 """
22     A simple IPC mechanism for communicating between two local processes. We
23     use marshal to serialize data - this means that both client and server must
24     run the same Python version, and that clients must be trusted (as
25     un-marshalling untrusted data can result in arbitrary code execution).
26 """
27 
28 from __future__ import annotations
29 
30 import asyncio
31 import fcntl
32 import json
33 import marshal
34 import os.path
35 import socket
36 import struct
37 from typing import Any
38 
39 from libqtile.log_utils import logger
40 from libqtile.utils import get_cache_dir
41 
42 HDRFORMAT = "!L"
43 HDRLEN = struct.calcsize(HDRFORMAT)
44 
45 SOCKBASE = "qtilesocket.%s"
46 
47 
48 class IPCError(Exception):
49     pass
50 
51 
52 def find_sockfile(display: str = None):
53     """
54     Finds the appropriate socket file for the given display.
55 
56     If unspecified, the socket file is determined as follows:
57 
58         - If WAYLAND_DISPLAY is set, use it.
59         - else if DISPLAY is set, use that.
60         - else check for the existence of a socket file for WAYLAND_DISPLAY=wayland-0
61           and if it exists, use it.
62         - else check for the existence of a socket file for DISPLAY=:0
63           and if it exists, use it.
64         - else raise an IPCError.
65 
66     """
67     cache_directory = get_cache_dir()
68 
69     if display:
70         return os.path.join(cache_directory, SOCKBASE % display)
71 
72     display = os.environ.get("WAYLAND_DISPLAY")
73     if display:
74         return os.path.join(cache_directory, SOCKBASE % display)
75 
76     display = os.environ.get("DISPLAY")
77     if display:
78         return os.path.join(cache_directory, SOCKBASE % display)
79 
80     sockfile = os.path.join(cache_directory, SOCKBASE % "wayland-0")
81     if os.path.exists(sockfile):
82         return sockfile
83 
84     sockfile = os.path.join(cache_directory, SOCKBASE % ":0")
85     if os.path.exists(sockfile):
86         return sockfile
87 
88     raise IPCError("Could not find socket file.")
89 
90 
91 class _IPC:
92     """A helper class to handle properly packing and unpacking messages"""
93 
94     @staticmethod
95     def unpack(data: bytes, *, is_json: bool | None = None) -> tuple[Any, bool]:
96         """Unpack the incoming message
97 
98         Parameters
99         ----------
100         data: bytes
101             The incoming message to unpack
102         is_json: bool | None
103             If the message should be unpacked as json.  By default, try to
104             unpack json and fallback gracefully to marshalled bytes.
105 
106         Returns
107         -------
108         tuple[Any, bool]
109             A tuple of the unpacked object and a boolean denoting if the
110             message was deserialized using json.  If True, the return message
111             should be packed as json.
112         """
113         if is_json is None or is_json:
114             try:
115                 return json.loads(data.decode()), True
116             except ValueError as e:
117                 if is_json:
118                     raise IPCError("Unable to decode json data") from e
119 
120         try:
121             assert len(data) >= HDRLEN
122             size = struct.unpack(HDRFORMAT, data[:HDRLEN])[0]
123             assert size >= len(data[HDRLEN:])
124             return marshal.loads(data[HDRLEN : HDRLEN + size]), False
125         except AssertionError as e:
126             raise IPCError("error reading reply! (probably the socket was disconnected)") from e
127 
128     @staticmethod
129     def pack(msg: Any, *, is_json: bool = False) -> bytes:
130         """Pack the object into a message to pass"""
131         if is_json:
132             json_obj = json.dumps(msg)
133             return json_obj.encode()
134 
135         msg_bytes = marshal.dumps(msg)
136         size = struct.pack(HDRFORMAT, len(msg_bytes))
137         return size + msg_bytes
138 
139 
140 class Client:
141     def __init__(self, socket_path: str, is_json=False) -> None:
142         """Create a new IPC client
143 
144         Parameters
145         ----------
146         socket_path: str
147             The file path to the file that is used to open the connection to
148             the running IPC server.
149         is_json: bool
150             Pack and unpack messages as json
151         """
152         self.socket_path = socket_path
153         self.is_json = is_json
154 
155     def call(self, data: Any) -> Any:
156         return self.send(data)
157 
158     def send(self, msg: Any) -> Any:
159         """Send the message and return the response from the server
160 
161         If any exception is raised by the server, that will propogate out of
162         this call.
163         """
164         return asyncio.run(self.async_send(msg))
165 
166     async def async_send(self, msg: Any) -> Any:
167         """Send the message to the server
168 
169         Connect to the server, then pack and send the message to the server,
170         then wait for and return the response from the server.
171         """
172         try:
173             reader, writer = await asyncio.wait_for(
174                 asyncio.open_unix_connection(path=self.socket_path), timeout=3
175             )
176         except (ConnectionRefusedError, FileNotFoundError):
177             raise IPCError("Could not open {}".format(self.socket_path))
178 
179         try:
180             send_data = _IPC.pack(msg, is_json=self.is_json)
181             writer.write(send_data)
182             writer.write_eof()
183 
184             read_data = await asyncio.wait_for(reader.read(), timeout=10)
185         except asyncio.TimeoutError:
186             raise IPCError("Server not responding")
187         finally:
188             # see the note in Server._server_callback()
189             writer.close()
190             await writer.wait_closed()
191 
192         data, _ = _IPC.unpack(read_data, is_json=self.is_json)
193 
194         return data
195 
196 
197 class Server:
198     def __init__(self, socket_path: str, handler) -> None:
199         self.socket_path = socket_path
200         self.handler = handler
201         self.server = None  # type: asyncio.AbstractServer | None
202 
203         if os.path.exists(socket_path):
204             os.unlink(socket_path)
205 
206         self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
207         flags = fcntl.fcntl(self.sock.fileno(), fcntl.F_GETFD)
208         fcntl.fcntl(self.sock.fileno(), fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
209         self.sock.bind(self.socket_path)
210 
211     async def _server_callback(
212         self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
213     ) -> None:
214         """Callback when a connection is made to the server
215 
216         Read the data sent from the client, execute the requested command, and
217         send the reply back to the client.
218         """
219         try:
220             logger.debug("Connection made to server")
221             data = await reader.read()
222             logger.debug("EOF received by server")
223 
224             req, is_json = _IPC.unpack(data)
225         except IPCError:
226             logger.warning("Invalid data received, closing connection")
227         else:
228             rep = self.handler(req)
229 
230             result = _IPC.pack(rep, is_json=is_json)
231 
232             logger.debug("Sending result on receive EOF")
233             writer.write(result)
234             logger.debug("Closing connection on receive EOF")
235             writer.write_eof()
236         finally:
237             writer.close()
238             await writer.wait_closed()
239 
240     async def __aenter__(self) -> "Server":
241         """Start and return the server"""
242         await self.start()
243         return self
244 
245     async def __aexit__(self, _exc_type, _exc_value, _tb) -> None:
246         """Close and shutdown the server"""
247         await self.close()
248 
249     async def start(self) -> None:
250         """Start the server"""
251         assert self.server is None
252 
253         logger.debug("Starting server")
254         server_coroutine = asyncio.start_unix_server(self._server_callback, sock=self.sock)
255         self.server = await server_coroutine
256 
257     async def close(self) -> None:
258         """Close and shutdown the server"""
259         assert self.server is not None
260 
261         logger.debug("Stopping server on close")
262         self.server.close()
263         await self.server.wait_closed()
264 
265         self.server = None
266
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/libqtile/ipc.py b/libqtile/ipc.py
--- a/libqtile/ipc.py
+++ b/libqtile/ipc.py
@@ -129,13 +129,20 @@
     def pack(msg: Any, *, is_json: bool = False) -> bytes:
         """Pack the object into a message to pass"""
         if is_json:
-            json_obj = json.dumps(msg)
+            json_obj = json.dumps(msg, default=_IPC._json_encoder)
             return json_obj.encode()
 
         msg_bytes = marshal.dumps(msg)
         size = struct.pack(HDRFORMAT, len(msg_bytes))
         return size + msg_bytes
 
+    @staticmethod
+    def _json_encoder(field: Any) -> Any:
+        """Convert non-serializable types to ones understood by stdlib json module"""
+        if isinstance(field, set):
+            return list(field)
+        raise ValueError(f"Tried to JSON serialize unsupported type {type(field)}: {field}")
+
 
 class Client:
     def __init__(self, socket_path: str, is_json=False) -> None:

{"golden_diff": "diff --git a/libqtile/ipc.py b/libqtile/ipc.py\n--- a/libqtile/ipc.py\n+++ b/libqtile/ipc.py\n@@ -129,13 +129,20 @@\n     def pack(msg: Any, *, is_json: bool = False) -> bytes:\n         \"\"\"Pack the object into a message to pass\"\"\"\n         if is_json:\n-            json_obj = json.dumps(msg)\n+            json_obj = json.dumps(msg, default=_IPC._json_encoder)\n             return json_obj.encode()\n \n         msg_bytes = marshal.dumps(msg)\n         size = struct.pack(HDRFORMAT, len(msg_bytes))\n         return size + msg_bytes\n \n+    @staticmethod\n+    def _json_encoder(field: Any) -> Any:\n+        \"\"\"Convert non-serializable types to ones understood by stdlib json module\"\"\"\n+        if isinstance(field, set):\n+            return list(field)\n+        raise ValueError(f\"Tried to JSON serialize unsupported type {type(field)}: {field}\")\n+\n \n class Client:\n     def __init__(self, socket_path: str, is_json=False) -> None:\n", "issue": "Groups cannot be listed using JSON IPC\nUsing the JSON serialization format in the IPC and trying to list groups yields exception \r\n```\r\nObject of type set is not JSON serializable\r\nNoneType: None\r\n```\r\nin the qtile logs and causes a `IPCError: Unable to decode json data` in the client end.\r\n\r\nReproduce with:\r\n```python\r\nfrom libqtile.command.client import (\r\n    InteractiveCommandClient,\r\n    Client,\r\n    find_sockfile,\r\n    IPCCommandInterface,\r\n)\r\nc = InteractiveCommandClient(\r\n    command=IPCCommandInterface(\r\n        Client(find_sockfile(), is_json=True)\r\n    )\r\n)\r\nc.groups()\r\n```\r\n\r\n\n", "before_files": [{"content": "# Copyright (c) 2008, Aldo Cortesi. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\n    A simple IPC mechanism for communicating between two local processes. We\n    use marshal to serialize data - this means that both client and server must\n    run the same Python version, and that clients must be trusted (as\n    un-marshalling untrusted data can result in arbitrary code execution).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport fcntl\nimport json\nimport marshal\nimport os.path\nimport socket\nimport struct\nfrom typing import Any\n\nfrom libqtile.log_utils import logger\nfrom libqtile.utils import get_cache_dir\n\nHDRFORMAT = \"!L\"\nHDRLEN = struct.calcsize(HDRFORMAT)\n\nSOCKBASE = \"qtilesocket.%s\"\n\n\nclass IPCError(Exception):\n    pass\n\n\ndef find_sockfile(display: str = None):\n    \"\"\"\n    Finds the appropriate socket file for the given display.\n\n    If unspecified, the socket file is determined as follows:\n\n        - If WAYLAND_DISPLAY is set, use it.\n        - else if DISPLAY is set, use that.\n        - else check for the existence of a socket file for WAYLAND_DISPLAY=wayland-0\n          and if it exists, use it.\n        - else check for the existence of a socket file for DISPLAY=:0\n          and if it exists, use it.\n        - else raise an IPCError.\n\n    \"\"\"\n    cache_directory = get_cache_dir()\n\n    if display:\n        return os.path.join(cache_directory, SOCKBASE % display)\n\n    display = os.environ.get(\"WAYLAND_DISPLAY\")\n    if display:\n        return os.path.join(cache_directory, SOCKBASE % display)\n\n    display = os.environ.get(\"DISPLAY\")\n    if display:\n        return os.path.join(cache_directory, SOCKBASE % display)\n\n    sockfile = os.path.join(cache_directory, SOCKBASE % \"wayland-0\")\n    if os.path.exists(sockfile):\n        return sockfile\n\n    sockfile = os.path.join(cache_directory, SOCKBASE % \":0\")\n    if os.path.exists(sockfile):\n        return sockfile\n\n    raise IPCError(\"Could not find socket file.\")\n\n\nclass _IPC:\n    \"\"\"A helper class to handle properly packing and unpacking messages\"\"\"\n\n    @staticmethod\n    def unpack(data: bytes, *, is_json: bool | None = None) -> tuple[Any, bool]:\n        \"\"\"Unpack the incoming message\n\n        Parameters\n        ----------\n        data: bytes\n            The incoming message to unpack\n        is_json: bool | None\n            If the message should be unpacked as json.  By default, try to\n            unpack json and fallback gracefully to marshalled bytes.\n\n        Returns\n        -------\n        tuple[Any, bool]\n            A tuple of the unpacked object and a boolean denoting if the\n            message was deserialized using json.  If True, the return message\n            should be packed as json.\n        \"\"\"\n        if is_json is None or is_json:\n            try:\n                return json.loads(data.decode()), True\n            except ValueError as e:\n                if is_json:\n                    raise IPCError(\"Unable to decode json data\") from e\n\n        try:\n            assert len(data) >= HDRLEN\n            size = struct.unpack(HDRFORMAT, data[:HDRLEN])[0]\n            assert size >= len(data[HDRLEN:])\n            return marshal.loads(data[HDRLEN : HDRLEN + size]), False\n        except AssertionError as e:\n            raise IPCError(\"error reading reply! (probably the socket was disconnected)\") from e\n\n    @staticmethod\n    def pack(msg: Any, *, is_json: bool = False) -> bytes:\n        \"\"\"Pack the object into a message to pass\"\"\"\n        if is_json:\n            json_obj = json.dumps(msg)\n            return json_obj.encode()\n\n        msg_bytes = marshal.dumps(msg)\n        size = struct.pack(HDRFORMAT, len(msg_bytes))\n        return size + msg_bytes\n\n\nclass Client:\n    def __init__(self, socket_path: str, is_json=False) -> None:\n        \"\"\"Create a new IPC client\n\n        Parameters\n        ----------\n        socket_path: str\n            The file path to the file that is used to open the connection to\n            the running IPC server.\n        is_json: bool\n            Pack and unpack messages as json\n        \"\"\"\n        self.socket_path = socket_path\n        self.is_json = is_json\n\n    def call(self, data: Any) -> Any:\n        return self.send(data)\n\n    def send(self, msg: Any) -> Any:\n        \"\"\"Send the message and return the response from the server\n\n        If any exception is raised by the server, that will propogate out of\n        this call.\n        \"\"\"\n        return asyncio.run(self.async_send(msg))\n\n    async def async_send(self, msg: Any) -> Any:\n        \"\"\"Send the message to the server\n\n        Connect to the server, then pack and send the message to the server,\n        then wait for and return the response from the server.\n        \"\"\"\n        try:\n            reader, writer = await asyncio.wait_for(\n                asyncio.open_unix_connection(path=self.socket_path), timeout=3\n            )\n        except (ConnectionRefusedError, FileNotFoundError):\n            raise IPCError(\"Could not open {}\".format(self.socket_path))\n\n        try:\n            send_data = _IPC.pack(msg, is_json=self.is_json)\n            writer.write(send_data)\n            writer.write_eof()\n\n            read_data = await asyncio.wait_for(reader.read(), timeout=10)\n        except asyncio.TimeoutError:\n            raise IPCError(\"Server not responding\")\n        finally:\n            # see the note in Server._server_callback()\n            writer.close()\n            await writer.wait_closed()\n\n        data, _ = _IPC.unpack(read_data, is_json=self.is_json)\n\n        return data\n\n\nclass Server:\n    def __init__(self, socket_path: str, handler) -> None:\n        self.socket_path = socket_path\n        self.handler = handler\n        self.server = None  # type: asyncio.AbstractServer | None\n\n        if os.path.exists(socket_path):\n            os.unlink(socket_path)\n\n        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)\n        flags = fcntl.fcntl(self.sock.fileno(), fcntl.F_GETFD)\n        fcntl.fcntl(self.sock.fileno(), fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)\n        self.sock.bind(self.socket_path)\n\n    async def _server_callback(\n        self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter\n    ) -> None:\n        \"\"\"Callback when a connection is made to the server\n\n        Read the data sent from the client, execute the requested command, and\n        send the reply back to the client.\n        \"\"\"\n        try:\n            logger.debug(\"Connection made to server\")\n            data = await reader.read()\n            logger.debug(\"EOF received by server\")\n\n            req, is_json = _IPC.unpack(data)\n        except IPCError:\n            logger.warning(\"Invalid data received, closing connection\")\n        else:\n            rep = self.handler(req)\n\n            result = _IPC.pack(rep, is_json=is_json)\n\n            logger.debug(\"Sending result on receive EOF\")\n            writer.write(result)\n            logger.debug(\"Closing connection on receive EOF\")\n            writer.write_eof()\n        finally:\n            writer.close()\n            await writer.wait_closed()\n\n    async def __aenter__(self) -> \"Server\":\n        \"\"\"Start and return the server\"\"\"\n        await self.start()\n        return self\n\n    async def __aexit__(self, _exc_type, _exc_value, _tb) -> None:\n        \"\"\"Close and shutdown the server\"\"\"\n        await self.close()\n\n    async def start(self) -> None:\n        \"\"\"Start the server\"\"\"\n        assert self.server is None\n\n        logger.debug(\"Starting server\")\n        server_coroutine = asyncio.start_unix_server(self._server_callback, sock=self.sock)\n        self.server = await server_coroutine\n\n    async def close(self) -> None:\n        \"\"\"Close and shutdown the server\"\"\"\n        assert self.server is not None\n\n        logger.debug(\"Stopping server on close\")\n        self.server.close()\n        await self.server.wait_closed()\n\n        self.server = None\n", "path": "libqtile/ipc.py"}], "after_files": [{"content": "# Copyright (c) 2008, Aldo Cortesi. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\n    A simple IPC mechanism for communicating between two local processes. We\n    use marshal to serialize data - this means that both client and server must\n    run the same Python version, and that clients must be trusted (as\n    un-marshalling untrusted data can result in arbitrary code execution).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport fcntl\nimport json\nimport marshal\nimport os.path\nimport socket\nimport struct\nfrom typing import Any\n\nfrom libqtile.log_utils import logger\nfrom libqtile.utils import get_cache_dir\n\nHDRFORMAT = \"!L\"\nHDRLEN = struct.calcsize(HDRFORMAT)\n\nSOCKBASE = \"qtilesocket.%s\"\n\n\nclass IPCError(Exception):\n    pass\n\n\ndef find_sockfile(display: str = None):\n    \"\"\"\n    Finds the appropriate socket file for the given display.\n\n    If unspecified, the socket file is determined as follows:\n\n        - If WAYLAND_DISPLAY is set, use it.\n        - else if DISPLAY is set, use that.\n        - else check for the existence of a socket file for WAYLAND_DISPLAY=wayland-0\n          and if it exists, use it.\n        - else check for the existence of a socket file for DISPLAY=:0\n          and if it exists, use it.\n        - else raise an IPCError.\n\n    \"\"\"\n    cache_directory = get_cache_dir()\n\n    if display:\n        return os.path.join(cache_directory, SOCKBASE % display)\n\n    display = os.environ.get(\"WAYLAND_DISPLAY\")\n    if display:\n        return os.path.join(cache_directory, SOCKBASE % display)\n\n    display = os.environ.get(\"DISPLAY\")\n    if display:\n        return os.path.join(cache_directory, SOCKBASE % display)\n\n    sockfile = os.path.join(cache_directory, SOCKBASE % \"wayland-0\")\n    if os.path.exists(sockfile):\n        return sockfile\n\n    sockfile = os.path.join(cache_directory, SOCKBASE % \":0\")\n    if os.path.exists(sockfile):\n        return sockfile\n\n    raise IPCError(\"Could not find socket file.\")\n\n\nclass _IPC:\n    \"\"\"A helper class to handle properly packing and unpacking messages\"\"\"\n\n    @staticmethod\n    def unpack(data: bytes, *, is_json: bool | None = None) -> tuple[Any, bool]:\n        \"\"\"Unpack the incoming message\n\n        Parameters\n        ----------\n        data: bytes\n            The incoming message to unpack\n        is_json: bool | None\n            If the message should be unpacked as json.  By default, try to\n            unpack json and fallback gracefully to marshalled bytes.\n\n        Returns\n        -------\n        tuple[Any, bool]\n            A tuple of the unpacked object and a boolean denoting if the\n            message was deserialized using json.  If True, the return message\n            should be packed as json.\n        \"\"\"\n        if is_json is None or is_json:\n            try:\n                return json.loads(data.decode()), True\n            except ValueError as e:\n                if is_json:\n                    raise IPCError(\"Unable to decode json data\") from e\n\n        try:\n            assert len(data) >= HDRLEN\n            size = struct.unpack(HDRFORMAT, data[:HDRLEN])[0]\n            assert size >= len(data[HDRLEN:])\n            return marshal.loads(data[HDRLEN : HDRLEN + size]), False\n        except AssertionError as e:\n            raise IPCError(\"error reading reply! (probably the socket was disconnected)\") from e\n\n    @staticmethod\n    def pack(msg: Any, *, is_json: bool = False) -> bytes:\n        \"\"\"Pack the object into a message to pass\"\"\"\n        if is_json:\n            json_obj = json.dumps(msg, default=_IPC._json_encoder)\n            return json_obj.encode()\n\n        msg_bytes = marshal.dumps(msg)\n        size = struct.pack(HDRFORMAT, len(msg_bytes))\n        return size + msg_bytes\n\n    @staticmethod\n    def _json_encoder(field: Any) -> Any:\n        \"\"\"Convert non-serializable types to ones understood by stdlib json module\"\"\"\n        if isinstance(field, set):\n            return list(field)\n        raise ValueError(f\"Tried to JSON serialize unsupported type {type(field)}: {field}\")\n\n\nclass Client:\n    def __init__(self, socket_path: str, is_json=False) -> None:\n        \"\"\"Create a new IPC client\n\n        Parameters\n        ----------\n        socket_path: str\n            The file path to the file that is used to open the connection to\n            the running IPC server.\n        is_json: bool\n            Pack and unpack messages as json\n        \"\"\"\n        self.socket_path = socket_path\n        self.is_json = is_json\n\n    def call(self, data: Any) -> Any:\n        return self.send(data)\n\n    def send(self, msg: Any) -> Any:\n        \"\"\"Send the message and return the response from the server\n\n        If any exception is raised by the server, that will propogate out of\n        this call.\n        \"\"\"\n        return asyncio.run(self.async_send(msg))\n\n    async def async_send(self, msg: Any) -> Any:\n        \"\"\"Send the message to the server\n\n        Connect to the server, then pack and send the message to the server,\n        then wait for and return the response from the server.\n        \"\"\"\n        try:\n            reader, writer = await asyncio.wait_for(\n                asyncio.open_unix_connection(path=self.socket_path), timeout=3\n            )\n        except (ConnectionRefusedError, FileNotFoundError):\n            raise IPCError(\"Could not open {}\".format(self.socket_path))\n\n        try:\n            send_data = _IPC.pack(msg, is_json=self.is_json)\n            writer.write(send_data)\n            writer.write_eof()\n\n            read_data = await asyncio.wait_for(reader.read(), timeout=10)\n        except asyncio.TimeoutError:\n            raise IPCError(\"Server not responding\")\n        finally:\n            # see the note in Server._server_callback()\n            writer.close()\n            await writer.wait_closed()\n\n        data, _ = _IPC.unpack(read_data, is_json=self.is_json)\n\n        return data\n\n\nclass Server:\n    def __init__(self, socket_path: str, handler) -> None:\n        self.socket_path = socket_path\n        self.handler = handler\n        self.server = None  # type: asyncio.AbstractServer | None\n\n        if os.path.exists(socket_path):\n            os.unlink(socket_path)\n\n        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)\n        flags = fcntl.fcntl(self.sock.fileno(), fcntl.F_GETFD)\n        fcntl.fcntl(self.sock.fileno(), fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)\n        self.sock.bind(self.socket_path)\n\n    async def _server_callback(\n        self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter\n    ) -> None:\n        \"\"\"Callback when a connection is made to the server\n\n        Read the data sent from the client, execute the requested command, and\n        send the reply back to the client.\n        \"\"\"\n        try:\n            logger.debug(\"Connection made to server\")\n            data = await reader.read()\n            logger.debug(\"EOF received by server\")\n\n            req, is_json = _IPC.unpack(data)\n        except IPCError:\n            logger.warning(\"Invalid data received, closing connection\")\n        else:\n            rep = self.handler(req)\n\n            result = _IPC.pack(rep, is_json=is_json)\n\n            logger.debug(\"Sending result on receive EOF\")\n            writer.write(result)\n            logger.debug(\"Closing connection on receive EOF\")\n            writer.write_eof()\n        finally:\n            writer.close()\n            await writer.wait_closed()\n\n    async def __aenter__(self) -> \"Server\":\n        \"\"\"Start and return the server\"\"\"\n        await self.start()\n        return self\n\n    async def __aexit__(self, _exc_type, _exc_value, _tb) -> None:\n        \"\"\"Close and shutdown the server\"\"\"\n        await self.close()\n\n    async def start(self) -> None:\n        \"\"\"Start the server\"\"\"\n        assert self.server is None\n\n        logger.debug(\"Starting server\")\n        server_coroutine = asyncio.start_unix_server(self._server_callback, sock=self.sock)\n        self.server = await server_coroutine\n\n    async def close(self) -> None:\n        \"\"\"Close and shutdown the server\"\"\"\n        assert self.server is not None\n\n        logger.debug(\"Stopping server on close\")\n        self.server.close()\n        await self.server.wait_closed()\n\n        self.server = None\n", "path": "libqtile/ipc.py"}]}