-
-
Notifications
You must be signed in to change notification settings - Fork 372
Implement highlevel unix socket listeners #3187
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
Open
CoolCat467
wants to merge
10
commits into
python-trio:main
Choose a base branch
from
CoolCat467:unix-socket-server
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
b60728d
Implement highlevel unix socket listeners
CoolCat467 b916c3f
Add newsfragment
CoolCat467 c922a52
Add path functionality to `SocketListener` instead of making `UnixSoc…
CoolCat467 fe7ef60
Add tests for `_highlevel_open_unix_listeners`
CoolCat467 ec76454
Revert `SocketListener` holding on to `path`, just ask unix socket.
CoolCat467 75cc5df
Fix pyright issue
CoolCat467 705bd96
Add comment to exports test, fix test issue, and only unlink file on …
CoolCat467 e8232b4
Help macos socket paths not be too long
CoolCat467 87e77d0
Fix macos mkstemp
CoolCat467 f1b13fa
Merge branch 'python-trio:main' into unix-socket-server
CoolCat467 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 @@ | ||
| Add ``trio.open_unix_listener``, ``trio.serve_unix``, and ``trio.UnixSocketListener`` to support ``SOCK_STREAM`` `Unix domain sockets <https://en.wikipedia.org/wiki/Unix_domain_socket>`__ |
This file contains hidden or 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 hidden or 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,133 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| import trio | ||
| import trio.socket as tsocket | ||
| from trio import TaskStatus | ||
|
|
||
| from ._highlevel_open_tcp_listeners import _compute_backlog | ||
|
|
||
| if TYPE_CHECKING: | ||
| from collections.abc import Awaitable, Callable | ||
|
|
||
|
|
||
| try: | ||
| from trio.socket import AF_UNIX | ||
|
|
||
| HAS_UNIX = True | ||
| except ImportError: | ||
| HAS_UNIX = False | ||
|
|
||
|
|
||
| async def open_unix_listener( | ||
| path: str | bytes | os.PathLike[str] | os.PathLike[bytes], | ||
| *, | ||
| mode: int | None = None, | ||
| backlog: int | None = None, | ||
| ) -> trio.SocketListener: | ||
| """Create :class:`SocketListener` objects to listen for connections. | ||
| Opens a connection to the specified | ||
| `Unix domain socket <https://en.wikipedia.org/wiki/Unix_domain_socket>`__. | ||
|
|
||
| You must have read/write permission on the specified file to connect. | ||
|
|
||
| Args: | ||
|
|
||
| path (str): Filename of UNIX socket to create and listen on. | ||
| Absolute or relative paths may be used. | ||
|
|
||
| mode (int or None): The socket file permissions. | ||
| UNIX permissions are usually specified in octal numbers. If | ||
| you leave this as ``None``, Trio will not change the mode from | ||
| the operating system's default. | ||
|
|
||
| backlog (int or None): The listen backlog to use. If you leave this as | ||
| ``None`` then Trio will pick a good default. (Currently: | ||
| whatever your system has configured as the maximum backlog.) | ||
|
|
||
| Returns: | ||
| :class:`UnixSocketListener` | ||
|
|
||
| Raises: | ||
| :class:`ValueError` If invalid arguments. | ||
| :class:`RuntimeError`: If AF_UNIX sockets are not supported. | ||
| :class:`FileNotFoundError`: If folder socket file is to be created in does not exist. | ||
| """ | ||
| if not HAS_UNIX: | ||
| raise RuntimeError("Unix sockets are not supported on this platform") | ||
|
|
||
| computed_backlog = _compute_backlog(backlog) | ||
|
|
||
| fspath = await trio.Path(os.fsdecode(path)).absolute() | ||
|
|
||
| folder = fspath.parent | ||
| if not await folder.exists(): | ||
| raise FileNotFoundError(f"Socket folder does not exist: {folder!r}") | ||
|
|
||
| str_path = str(fspath) | ||
|
|
||
| # much more simplified logic vs tcp sockets - one socket family and only one | ||
| # possible location to connect to | ||
| sock = tsocket.socket(AF_UNIX, tsocket.SOCK_STREAM) | ||
| try: | ||
| await sock.bind(str_path) | ||
|
|
||
| if mode is not None: | ||
| await fspath.chmod(mode) | ||
|
|
||
| sock.listen(computed_backlog) | ||
|
|
||
| return trio.SocketListener(sock) | ||
| except BaseException: | ||
| sock.close() | ||
| if os.path.exists(str_path): | ||
| os.unlink(str_path) | ||
| raise | ||
|
|
||
|
|
||
| async def serve_unix( | ||
| handler: Callable[[trio.SocketStream], Awaitable[object]], | ||
| path: str | bytes | os.PathLike[str] | os.PathLike[bytes], | ||
| *, | ||
| backlog: int | None = None, | ||
| handler_nursery: trio.Nursery | None = None, | ||
| task_status: TaskStatus[list[trio.SocketListener]] = trio.TASK_STATUS_IGNORED, | ||
| ) -> None: | ||
| """Listen for incoming UNIX connections, and for each one start a task | ||
| running ``handler(stream)``. | ||
| This is a thin convenience wrapper around :func:`open_unix_listener` and | ||
| :func:`serve_listeners` – see them for full details. | ||
| .. warning:: | ||
| If ``handler`` raises an exception, then this function doesn't do | ||
| anything special to catch it – so by default the exception will | ||
| propagate out and crash your server. If you don't want this, then catch | ||
| exceptions inside your ``handler``, or use a ``handler_nursery`` object | ||
| that responds to exceptions in some other way. | ||
| When used with ``nursery.start`` you get back the newly opened listeners. | ||
| Args: | ||
| handler: The handler to start for each incoming connection. Passed to | ||
| :func:`serve_listeners`. | ||
| path: The socket file name. | ||
| Passed to :func:`open_unix_listener`. | ||
| backlog: The listen backlog, or None to have a good default picked. | ||
| Passed to :func:`open_tcp_listener`. | ||
| handler_nursery: The nursery to start handlers in, or None to use an | ||
| internal nursery. Passed to :func:`serve_listeners`. | ||
| task_status: This function can be used with ``nursery.start``. | ||
| Returns: | ||
| This function only returns when cancelled. | ||
| Raises: | ||
| RuntimeError: If AF_UNIX sockets are not supported. | ||
| """ | ||
| if not HAS_UNIX: | ||
| raise RuntimeError("Unix sockets are not supported on this platform") | ||
|
|
||
| listener = await open_unix_listener(path, backlog=backlog) | ||
| await trio.serve_listeners( | ||
| handler, | ||
| [listener], | ||
| handler_nursery=handler_nursery, | ||
| task_status=task_status, | ||
| ) |
This file contains hidden or 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 hidden or 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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IMO this is cleaner than the definition in
_highlevel_open_unix_listeners.py