akikaze 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
akikaze-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.3
2
+ Name: akikaze
3
+ Version: 0.1.0
4
+ Summary: A FastAPI-like web framework built on Soyokaze.
5
+ Requires-Dist: soyokaze>=1.0.0,<2.0.0
6
+ Requires-Dist: nercone-modern>=7.0.0,<8.0.0
7
+ Requires-Python: >=3.10
8
+ Project-URL: GitHub, https://github.com/nercone-dev/akikaze/
9
+ Description-Content-Type: text/markdown
10
+
11
+ # Akikaze
12
+
13
+ A FastAPI-like web framework built on [Soyokaze](https://github.com/nercone-dev/soyokaze).
14
+
15
+ ```python
16
+ import dataclasses
17
+ from typing import Dict, Optional
18
+
19
+ from akikaze import Akikaze, HTTPException
20
+
21
+ app = Akikaze()
22
+
23
+ @dataclasses.dataclass
24
+ class Item:
25
+ name: str
26
+ price: float
27
+
28
+ items: Dict[int, Item] = {}
29
+
30
+ @app.get("/items/{item_id}")
31
+ async def read_item(item_id: int, q: Optional[str] = None) -> dict:
32
+ if item_id not in items:
33
+ raise HTTPException(404, "no such item")
34
+ return {"item": items[item_id], "q": q}
35
+
36
+ @app.post("/items/{item_id}", status_code=201)
37
+ async def create_item(item_id: int, item: Item) -> Item:
38
+ items[item_id] = item
39
+ return item
40
+ ```
41
+
42
+ ```bash
43
+ akikaze main:app --port 8000 --reload
44
+ akikaze main:app -b tcp://[::]:443 -b quic://[::]:443 -b unix:/run/app.sock --certificate cert.pem --key key.pem
45
+ ```
46
+
47
+ - Parameters are read from the path, query, headers, cookies, a JSON body or a
48
+ form, and converted to their annotated types; a request that does not fit is
49
+ answered `422` with every problem listed.
50
+ - Dependencies (`Depends`), including ones that `yield` for cleanup.
51
+ - Routers with prefixes, middleware, exception handlers, WebSocket routes and a
52
+ lifespan.
53
+ - Any number of TCP, QUIC and Unix domain socket binds, on any addresses.
54
+ - `--reload` restarts on changes, keeping the old code serving until the new
55
+ code listens where the platform allows.
56
+ - HTTP/1.1, HTTP/2 and HTTP/3, TLS and WebSocket come from Soyokaze.
57
+
58
+ Python 3.10 or newer. See [docs](docs/README.md).
@@ -0,0 +1,48 @@
1
+ # Akikaze
2
+
3
+ A FastAPI-like web framework built on [Soyokaze](https://github.com/nercone-dev/soyokaze).
4
+
5
+ ```python
6
+ import dataclasses
7
+ from typing import Dict, Optional
8
+
9
+ from akikaze import Akikaze, HTTPException
10
+
11
+ app = Akikaze()
12
+
13
+ @dataclasses.dataclass
14
+ class Item:
15
+ name: str
16
+ price: float
17
+
18
+ items: Dict[int, Item] = {}
19
+
20
+ @app.get("/items/{item_id}")
21
+ async def read_item(item_id: int, q: Optional[str] = None) -> dict:
22
+ if item_id not in items:
23
+ raise HTTPException(404, "no such item")
24
+ return {"item": items[item_id], "q": q}
25
+
26
+ @app.post("/items/{item_id}", status_code=201)
27
+ async def create_item(item_id: int, item: Item) -> Item:
28
+ items[item_id] = item
29
+ return item
30
+ ```
31
+
32
+ ```bash
33
+ akikaze main:app --port 8000 --reload
34
+ akikaze main:app -b tcp://[::]:443 -b quic://[::]:443 -b unix:/run/app.sock --certificate cert.pem --key key.pem
35
+ ```
36
+
37
+ - Parameters are read from the path, query, headers, cookies, a JSON body or a
38
+ form, and converted to their annotated types; a request that does not fit is
39
+ answered `422` with every problem listed.
40
+ - Dependencies (`Depends`), including ones that `yield` for cleanup.
41
+ - Routers with prefixes, middleware, exception handlers, WebSocket routes and a
42
+ lifespan.
43
+ - Any number of TCP, QUIC and Unix domain socket binds, on any addresses.
44
+ - `--reload` restarts on changes, keeping the old code serving until the new
45
+ code listens where the platform allows.
46
+ - HTTP/1.1, HTTP/2 and HTTP/3, TLS and WebSocket come from Soyokaze.
47
+
48
+ Python 3.10 or newer. See [docs](docs/README.md).
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.9.5,<0.10.0"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "akikaze"
7
+ description = "A FastAPI-like web framework built on Soyokaze."
8
+ readme = "README.md"
9
+ version = "0.1.0"
10
+ requires-python = ">=3.10"
11
+ dependencies = [
12
+ "soyokaze>=1.0.0,<2.0.0",
13
+ "nercone-modern>=7.0.0,<8.0.0",
14
+ ]
15
+
16
+ [project.urls]
17
+ GitHub = "https://github.com/nercone-dev/akikaze/"
18
+
19
+ [project.scripts]
20
+ akikaze = "akikaze.cli:main"
21
+
22
+ [dependency-groups]
23
+ dev = ["pytest>=9.2.0"]
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.9.5,<0.10.0"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "akikaze"
7
+ description = "A FastAPI-like web framework built on Soyokaze."
8
+ readme = "README.md"
9
+ version = "0.1.0"
10
+ requires-python = ">=3.10"
11
+ dependencies = [
12
+ "soyokaze>=1.0.0,<2.0.0",
13
+ "nercone-modern>=7.0.0,<8.0.0",
14
+ ]
15
+
16
+ [project.urls]
17
+ 'GitHub' = 'https://github.com/nercone-dev/akikaze/'
18
+
19
+ [project.scripts]
20
+ akikaze = "akikaze.cli:main"
21
+
22
+ [dependency-groups]
23
+ dev = [
24
+ "pytest>=9.2.0",
25
+ ]
@@ -0,0 +1,43 @@
1
+ """A FastAPI-like web framework built on Soyokaze.
2
+
3
+ ::
4
+
5
+ from akikaze import Akikaze
6
+
7
+ app = Akikaze()
8
+
9
+ @app.get("/items/{item_id}")
10
+ async def read_item(item_id: int, q: Optional[str] = None) -> dict:
11
+ return {"item_id": item_id, "q": q}
12
+
13
+ Run it with ``akikaze module:app`` (``--reload`` to restart on changes), or
14
+ ``app.run()``.
15
+ """
16
+
17
+ from soyokaze import FileResponse, FormField, HTMLResponse, JSONResponse, MarkdownResponse, PlainTextResponse, RedirectResponse, Response, WebSocketConnection
18
+
19
+ from .app import Akikaze, ExceptionHandler, Lifespan
20
+ from .bind import Bind
21
+ from .convert import Converter, Encoder
22
+ from .dependant import Dependant, Field, RequestContext
23
+ from .exceptions import HTTPException, Issue, RequestValidationError, ValidationError, WebSocketException
24
+ from .params import Body, Cookie, Depends, Form, Header, Param, Path, Query
25
+ from .pattern import PathPattern
26
+ from .reload import Reloader, Watcher
27
+ from .routing import Route, Router, WebSocketRoute
28
+ from .serving import BindError, Serving
29
+ from .types import Handler, Middleware, Request, WebSocketHandler
30
+
31
+ __all__ = [
32
+ "Akikaze", "ExceptionHandler", "Lifespan",
33
+ "Bind", "BindError", "Serving",
34
+ "Reloader", "Watcher",
35
+ "Converter", "Encoder",
36
+ "Dependant", "Field", "RequestContext",
37
+ "HTTPException", "Issue", "RequestValidationError", "ValidationError", "WebSocketException",
38
+ "Body", "Cookie", "Depends", "Form", "Header", "Param", "Path", "Query",
39
+ "PathPattern",
40
+ "Route", "Router", "WebSocketRoute",
41
+ "Handler", "Middleware", "Request", "WebSocketHandler",
42
+ "FileResponse", "FormField", "HTMLResponse", "JSONResponse", "MarkdownResponse", "PlainTextResponse", "RedirectResponse", "Response", "WebSocketConnection",
43
+ ]
@@ -0,0 +1,4 @@
1
+ import sys
2
+ from .cli import main
3
+
4
+ sys.exit(main())
@@ -0,0 +1,256 @@
1
+ import asyncio
2
+ import contextlib
3
+ import signal
4
+ import sys
5
+ from typing import Any, AsyncContextManager, Awaitable, Callable, Dict, List, Optional, Sequence, Type, Union
6
+
7
+ import soyokaze
8
+ from soyokaze import CloseCode, JSONResponse, Port, Response, ServerConfig, WebSocketConnection
9
+
10
+ from .bind import Bind
11
+ from .dependant import RequestContext
12
+ from .exceptions import HTTPException, RequestValidationError, WebSocketException
13
+ from .params import Depends
14
+ from .pattern import PathPattern
15
+ from .routing import Router
16
+ from .serving import Serving
17
+ from .types import Handler, Middleware, Request
18
+
19
+ ExceptionHandler = Callable[[Request, Any], Awaitable[Response]]
20
+ """Turns an exception raised while answering a request into the response."""
21
+ # Any: each handler takes the exception class it is registered for.
22
+
23
+ Lifespan = Callable[["Akikaze"], AsyncContextManager[None]]
24
+ """Runs around serving: what comes before its ``yield`` before the server
25
+ starts, and what comes after once it has stopped."""
26
+
27
+ class Akikaze(Router, soyokaze.Handler):
28
+ """A web application: routes, middleware and exception handlers, served
29
+ by Soyokaze.
30
+
31
+ Pass it to :meth:`soyokaze.Server.serve` like any handler, or run it with
32
+ :meth:`serve`, :meth:`run` or the ``akikaze`` command.
33
+
34
+ ``dependencies`` run before every endpoint. ``websocket_any_origin`` is
35
+ Soyokaze's switch: ``False`` refuses WebSocket handshakes from pages on
36
+ other hosts. ``form_limits`` bound the forms read for :class:`Form`
37
+ parameters. ``json_max_depth`` is how deeply a JSON body may nest arrays
38
+ and objects; a deeper one is answered ``422``.
39
+ """
40
+
41
+ def __init__(self, *, dependencies: Sequence[Depends] = (), lifespan: Optional[Lifespan] = None, websocket_any_origin: bool = False, form_limits: Optional[soyokaze.MultipartLimits] = None, json_max_depth: int = RequestContext.JSON_MAX_DEPTH) -> None:
42
+ Router.__init__(self, dependencies=dependencies)
43
+ self.middlewares: List[Middleware] = []
44
+ self.chain: Handler = self.dispatch
45
+ self.exception_handlers: Dict[Type[BaseException], ExceptionHandler] = {
46
+ HTTPException: Akikaze.http_exception,
47
+ RequestValidationError: Akikaze.validation_exception,
48
+ }
49
+ self.lifespan: Optional[Lifespan] = lifespan
50
+ self.websocket_any_origin: bool = websocket_any_origin
51
+ self.form_limits: Optional[soyokaze.MultipartLimits] = form_limits
52
+ self.json_max_depth: int = json_max_depth
53
+
54
+ @staticmethod
55
+ def wrap_middleware(middleware: Middleware, next_handler: Handler) -> Handler:
56
+ """``next_handler`` with ``middleware`` run around it."""
57
+ async def handler(request: Request) -> Response:
58
+ return await middleware(request, next_handler)
59
+ return handler
60
+
61
+ def add_middleware(self, middleware: Middleware) -> Middleware:
62
+ """Runs ``middleware`` around every request.
63
+
64
+ A middleware is called with the request and ``call_next``, which
65
+ answers it with everything inside; what it returns is the response.
66
+ The middleware added last runs outermost. Exception handlers run
67
+ inside every middleware, so a middleware sees their responses.
68
+ """
69
+ self.middlewares.append(middleware)
70
+ self.chain = Akikaze.wrap_middleware(middleware, self.chain)
71
+ return middleware
72
+
73
+ def middleware(self, kind: str = "http") -> Callable[[Middleware], Middleware]:
74
+ """A decorator form of :meth:`add_middleware`. ``kind`` is there so
75
+ that FastAPI's ``@app.middleware("http")`` reads the same; ``"http"``
76
+ is the only kind."""
77
+ if kind != "http":
78
+ raise ValueError(f"middleware is for 'http' only, not {kind!r}")
79
+ return self.add_middleware
80
+
81
+ def add_exception_handler(self, kind: Type[BaseException], handler: ExceptionHandler) -> ExceptionHandler:
82
+ """Answers with ``handler`` when answering a request raises ``kind``.
83
+
84
+ The handler registered for the nearest class in the exception's
85
+ method resolution order is used. Without one, the exception reaches
86
+ Soyokaze, which answers ``500`` and prints the traceback.
87
+ """
88
+ self.exception_handlers[kind] = handler
89
+ return handler
90
+
91
+ def exception_handler(self, kind: Type[BaseException]) -> Callable[[ExceptionHandler], ExceptionHandler]:
92
+ """A decorator form of :meth:`add_exception_handler`."""
93
+ def decorator(handler: ExceptionHandler) -> ExceptionHandler:
94
+ return self.add_exception_handler(kind, handler)
95
+ return decorator
96
+
97
+ def find_exception_handler(self, kind: Type[BaseException]) -> Optional[ExceptionHandler]:
98
+ for base in kind.__mro__:
99
+ handler = self.exception_handlers.get(base)
100
+ if handler is not None:
101
+ return handler
102
+ return None
103
+
104
+ @staticmethod
105
+ async def http_exception(request: Request, error: HTTPException) -> Response:
106
+ """The default handler of :class:`HTTPException`."""
107
+ if error.status_code in (204, 304):
108
+ return Response(error.status_code, headers=error.headers)
109
+ return JSONResponse({"detail": error.detail}, status_code=error.status_code, headers=error.headers)
110
+
111
+ @staticmethod
112
+ async def validation_exception(request: Request, error: RequestValidationError) -> Response:
113
+ """The default handler of :class:`RequestValidationError`: ``422``."""
114
+ return JSONResponse({"detail": [issue.to_dict() for issue in error.issues]}, status_code=422)
115
+
116
+ async def dispatch(self, request: Request) -> Response:
117
+ """Answers ``request`` with its route, and exceptions with their handlers."""
118
+ try:
119
+ path = request.path()
120
+ if path == "*" and request.method == soyokaze.Method.OPTIONS:
121
+ # RFC 9110 §9.3.7: OPTIONS * asks about the server, not a resource.
122
+ return Response(204)
123
+ segments = PathPattern.split(path)
124
+ if segments is None:
125
+ raise HTTPException(400, "the path is not valid")
126
+ route, params, allowed = self.match(request.method.as_str(), segments)
127
+ if route is None:
128
+ if allowed:
129
+ raise HTTPException(405, headers={"allow": ", ".join(sorted(allowed))})
130
+ raise HTTPException(404)
131
+ request.path_params = params
132
+ return await route.handle(request, self.form_limits, self.json_max_depth)
133
+ except Exception as error:
134
+ handler = self.find_exception_handler(type(error))
135
+ if handler is None:
136
+ raise
137
+ return await handler(request, error)
138
+
139
+ async def on_request(self, request: soyokaze.Request) -> Response:
140
+ return await self.chain(Request.of(request))
141
+
142
+ async def accept_websocket(self, request: soyokaze.Request) -> bool:
143
+ segments = PathPattern.split(request.path())
144
+ if segments is None:
145
+ return False
146
+ route, _ = self.match_websocket(segments)
147
+ return route is not None
148
+
149
+ async def on_websocket(self, websocket: WebSocketConnection, request: soyokaze.Request) -> None:
150
+ extended = Request.of(request)
151
+ segments = PathPattern.split(extended.path())
152
+ route, params = self.match_websocket(segments) if segments is not None else (None, {})
153
+ if route is None:
154
+ await websocket.close(CloseCode.POLICY_VIOLATION, "")
155
+ return
156
+ extended.path_params = params
157
+ try:
158
+ await route.handle(websocket, extended)
159
+ except RequestValidationError:
160
+ await websocket.close(CloseCode.POLICY_VIOLATION, "invalid parameters")
161
+ except HTTPException:
162
+ # A dependency shared with HTTP routes refused the request; a
163
+ # WebSocket has no status to answer with, so it is closed.
164
+ await websocket.close(CloseCode.POLICY_VIOLATION, "")
165
+ except WebSocketException as error:
166
+ await websocket.close(CloseCode(error.code), error.reason)
167
+
168
+ def lifespan_context(self) -> AsyncContextManager[None]:
169
+ """The application's lifespan, or one that does nothing."""
170
+ if self.lifespan is None:
171
+ return contextlib.nullcontext()
172
+ return self.lifespan(self)
173
+
174
+ async def serve(self, binds: Sequence[Union[Bind, Port, str]], config: Optional[ServerConfig] = None, *, ready: Optional[Callable[[Serving], None]] = None) -> None:
175
+ """Serves on every bind until the task running this is cancelled.
176
+
177
+ ``binds`` are :class:`Bind` objects, their text (``"tcp://[::]:8000"``,
178
+ ``"quic://0.0.0.0:8443"``, ``"unix:/run/app.sock"``) or
179
+ :class:`soyokaze.Port` objects, which listen on ``config.address``;
180
+ see :class:`Serving` for how they are served.
181
+
182
+ The lifespan is entered first and left last. Cancelling is how
183
+ serving is asked to stop, so the servers are closed and the lifespan
184
+ left as on a normal exit, and the cancellation is raised after. When
185
+ a bind fails, the lifespan is left the same way before
186
+ :class:`BindError` is raised.
187
+ ``ready`` is called with the :class:`Serving` once every bind
188
+ listens, to learn the ports bound.
189
+ """
190
+ stopped: Optional[BaseException] = None
191
+ async with self.lifespan_context():
192
+ try:
193
+ serving = await Serving.start(self, binds, config)
194
+ except Exception as error:
195
+ # Binding failed: leave the lifespan as on a normal exit, so
196
+ # what it started is stopped, then raise the failure.
197
+ stopped = error
198
+ else:
199
+ async with serving:
200
+ if ready is not None:
201
+ ready(serving)
202
+ try:
203
+ await asyncio.Event().wait()
204
+ except asyncio.CancelledError as error:
205
+ stopped = error
206
+ if stopped is not None:
207
+ raise stopped
208
+
209
+ async def serve_until_signalled(self, binds: Sequence[Union[Bind, Port, str]], config: Optional[ServerConfig] = None, *, ready: Optional[Callable[[Serving], None]] = None) -> None:
210
+ """:meth:`serve` until the process receives ``SIGINT`` or ``SIGTERM``,
211
+ then returns once the servers have closed and the lifespan is left.
212
+
213
+ The handlers are installed even when ``SIGINT`` was inherited as
214
+ ignored, as it is by a process a shell starts in the background, so
215
+ both signals always stop the server the same way. A signal that
216
+ arrives while stopping is ignored: a second cancellation would cut
217
+ the close and the lifespan short. Cancelling the task running this
218
+ also stops it, and the cancellation is raised then.
219
+ """
220
+ loop = asyncio.get_running_loop()
221
+ task = asyncio.current_task()
222
+ if task is None:
223
+ raise RuntimeError("serve_until_signalled runs in a task")
224
+ signalled = asyncio.Event()
225
+
226
+ def stop() -> None:
227
+ if signalled.is_set():
228
+ return
229
+ signalled.set()
230
+ task.cancel()
231
+
232
+ numbers = (signal.SIGINT, signal.SIGTERM)
233
+ for number in numbers:
234
+ loop.add_signal_handler(number, stop)
235
+ try:
236
+ await self.serve(binds, config, ready=ready)
237
+ except asyncio.CancelledError:
238
+ if not signalled.is_set():
239
+ raise
240
+ if sys.version_info >= (3, 11):
241
+ # Python 3.10 does not count cancellations, so has none to undo.
242
+ task.uncancel()
243
+ finally:
244
+ for number in numbers:
245
+ loop.remove_signal_handler(number)
246
+
247
+ def run(self, *binds: Union[Bind, Port, str], config: Optional[ServerConfig] = None) -> None:
248
+ """Serves on ``binds`` until ``SIGINT`` (Ctrl+C) or ``SIGTERM``.
249
+
250
+ With no binds, serves TCP port 8000 on ``config.address``
251
+ (``127.0.0.1`` by default)::
252
+
253
+ app.run()
254
+ app.run("tcp://[::]:8000", "quic://[::]:8000", "unix:/run/app.sock", config=config)
255
+ """
256
+ asyncio.run(self.serve_until_signalled(list(binds) if binds else [Bind.TCP(8000)], config))
@@ -0,0 +1,188 @@
1
+ import ipaddress
2
+ import os
3
+ from typing import Dict, Optional, Tuple, Union
4
+
5
+ from soyokaze import Port, PortKind
6
+
7
+ class Bind:
8
+ """Where a server listens: a transport and an address on it.
9
+
10
+ A :class:`soyokaze.Port` names a transport and a port number; the
11
+ address TCP and QUIC ports bind to is a :class:`soyokaze.ServerConfig`
12
+ setting shared by every port of one server. A bind carries its own
13
+ ``host``, so one application can listen on several addresses. ``host``
14
+ is ``None`` for a bind that takes the configuration's address (as a
15
+ plain :class:`soyokaze.Port` does), and always ``None`` for a Unix
16
+ domain socket, which has a ``path`` instead.
17
+
18
+ Written as text (:meth:`parse`, :meth:`__str__`)::
19
+
20
+ tcp://127.0.0.1:8000 TCP (HTTP/1.1 and HTTP/2)
21
+ 127.0.0.1:8000 the same
22
+ quic://[::]:8443 UDP carrying QUIC (HTTP/3)
23
+ unix:/run/app.sock a Unix domain socket (HTTP/1.1 and HTTP/2)
24
+ """
25
+
26
+ SCHEMES: Dict[str, PortKind] = {"tcp": PortKind.TCP, "quic": PortKind.QUIC}
27
+
28
+ def __init__(self, kind: PortKind, *, port: int = 0, host: Optional[str] = None, path: Optional[str] = None) -> None:
29
+ if kind == PortKind.UDS:
30
+ if not path:
31
+ raise ValueError("a Unix domain socket needs a path")
32
+ if host is not None or port != 0:
33
+ raise ValueError("a Unix domain socket has a path, not a host and port")
34
+ else:
35
+ if path is not None:
36
+ raise ValueError(f"a {kind.name} bind has a host and port, not a path")
37
+ if not isinstance(port, int) or isinstance(port, bool):
38
+ raise TypeError(f"the port is an int, not {type(port).__name__}")
39
+ if not 0 <= port <= 65535:
40
+ raise ValueError(f"port {port} is not between 0 and 65535")
41
+ if host is not None:
42
+ host = Bind.address(host)
43
+ self.kind: PortKind = kind
44
+ self.port: int = port
45
+ self.host: Optional[str] = host
46
+ self.path: Optional[str] = path
47
+
48
+ @classmethod
49
+ def address(cls, host: str) -> str:
50
+ """``host`` as an IP address in its usual text form (``::1`` for
51
+ ``0:0:0:0:0:0:0:1``), so one address is always written one way.
52
+
53
+ Raises :class:`ValueError` for anything else: Soyokaze binds IP
54
+ addresses, not names, and refuses an IPv6 zone (``fe80::1%en0``).
55
+ """
56
+ if "%" in host:
57
+ raise ValueError(f"{host!r}: an IPv6 zone is not supported")
58
+ try:
59
+ return str(ipaddress.ip_address(host))
60
+ except ValueError:
61
+ raise ValueError(f"{host!r} is not an IP address (names such as localhost are not resolved)") from None
62
+
63
+ @classmethod
64
+ def TCP(cls, port: int, host: Optional[str] = None) -> "Bind":
65
+ """A TCP port, on ``host`` or the configuration's address."""
66
+ return cls(PortKind.TCP, port=port, host=host)
67
+
68
+ @classmethod
69
+ def QUIC(cls, port: int, host: Optional[str] = None) -> "Bind":
70
+ """A UDP port carrying QUIC, on ``host`` or the configuration's address."""
71
+ return cls(PortKind.QUIC, port=port, host=host)
72
+
73
+ @classmethod
74
+ def UDS(cls, path: Union[str, "os.PathLike[str]"]) -> "Bind":
75
+ """A Unix domain socket at ``path``."""
76
+ return cls(PortKind.UDS, path=os.fspath(path))
77
+
78
+ @classmethod
79
+ def of(cls, value: Union["Bind", Port, str]) -> "Bind":
80
+ """``value`` as a bind: a bind as it is, a :class:`soyokaze.Port`
81
+ without a host, or text read by :meth:`parse`."""
82
+ if isinstance(value, Bind):
83
+ return value
84
+ if isinstance(value, Port):
85
+ if value.kind == PortKind.UDS:
86
+ return cls.UDS(value.path or "")
87
+ return cls(value.kind, port=value.number)
88
+ if isinstance(value, str):
89
+ return cls.parse(value)
90
+ raise TypeError(f"{value!r} is not a Bind, a Port or text")
91
+
92
+ @classmethod
93
+ def parse(cls, text: str) -> "Bind":
94
+ """The bind ``text`` names; see the class for the forms.
95
+
96
+ Raises :class:`ValueError` for anything else. The host and the port
97
+ are both required: a bind written down says where it listens.
98
+ """
99
+ if text.startswith("unix:"):
100
+ path = text[len("unix:"):]
101
+ if path.startswith("//"):
102
+ # unix:///run/app.sock, the URL form of /run/app.sock.
103
+ path = path[2:]
104
+ return cls.UDS(path)
105
+ scheme, separator, rest = text.partition("://")
106
+ if not separator:
107
+ scheme, rest = "tcp", text
108
+ kind = cls.SCHEMES.get(scheme)
109
+ if kind is None:
110
+ raise ValueError(f"{text!r}: the scheme is tcp, quic or unix, not {scheme!r}")
111
+ host, port = cls.split_address(text, rest)
112
+ return cls(kind, port=port, host=host)
113
+
114
+ @classmethod
115
+ def split_address(cls, text: str, address: str) -> Tuple[str, int]:
116
+ """The host and port of ``host:port`` or ``[IPv6]:port``."""
117
+ if address.startswith("["):
118
+ end = address.find("]")
119
+ if end < 0 or address[end + 1:end + 2] != ":":
120
+ raise ValueError(f"{text!r}: an IPv6 host is written [address]:port")
121
+ host, number = address[1:end], address[end + 2:]
122
+ if ":" not in host:
123
+ raise ValueError(f"{text!r}: only an IPv6 host is written in brackets")
124
+ else:
125
+ host, separator, number = address.rpartition(":")
126
+ if not separator:
127
+ raise ValueError(f"{text!r}: no port; write host:port")
128
+ if ":" in host:
129
+ raise ValueError(f"{text!r}: an IPv6 host is written [address]:port")
130
+ if not host:
131
+ raise ValueError(f"{text!r}: no host; write host:port")
132
+ # isdigit alone also takes other scripts' digits, which int() reads.
133
+ if not (number.isascii() and number.isdigit()):
134
+ raise ValueError(f"{text!r}: the port {number!r} is not a number")
135
+ return host, int(number)
136
+
137
+ def to_port(self) -> Port:
138
+ """The :class:`soyokaze.Port` to serve this on (without the host)."""
139
+ if self.kind == PortKind.UDS:
140
+ return Port.UDS(self.path or "")
141
+ return Port(self.kind, number=self.port)
142
+
143
+ DEFAULT_HOST: str = "127.0.0.1"
144
+ """The address Soyokaze binds TCP and QUIC ports to when the
145
+ configuration names none."""
146
+
147
+ def resolved(self, default_host: Optional[str]) -> "Bind":
148
+ """This bind with its host filled in: ``default_host`` (the
149
+ configuration's address) or else :attr:`DEFAULT_HOST`, for a TCP or
150
+ QUIC bind that has none. Others are returned as they are."""
151
+ if self.kind == PortKind.UDS or self.host is not None:
152
+ return self
153
+ return Bind(self.kind, port=self.port, host=default_host if default_host is not None else Bind.DEFAULT_HOST)
154
+
155
+ def same_place(self, other: "Bind", default_host: Optional[str]) -> bool:
156
+ """Whether binding both would bind one place twice: the same socket
157
+ path, or the same transport, host and port. A port of zero is a
158
+ fresh port each time, so never the same place."""
159
+ if self.kind != other.kind:
160
+ return False
161
+ if self.kind == PortKind.UDS:
162
+ return os.path.abspath(self.path or "") == os.path.abspath(other.path or "")
163
+ here, there = self.resolved(default_host), other.resolved(default_host)
164
+ return self.port != 0 and self.port == other.port and here.host == there.host
165
+
166
+ def __str__(self) -> str:
167
+ if self.kind == PortKind.UDS:
168
+ # A path starting with // would read back as unix://path, which
169
+ # parse takes for the URL form: write that form instead.
170
+ prefix = "unix://" if (self.path or "").startswith("//") else "unix:"
171
+ return f"{prefix}{self.path}"
172
+ # A bind without a host is written with an empty one, which parse
173
+ # refuses: resolved() says which address it stands for.
174
+ host = self.host if self.host is not None else ""
175
+ if ":" in host:
176
+ host = f"[{host}]"
177
+ return f"{self.kind.name.lower()}://{host}:{self.port}"
178
+
179
+ def __repr__(self) -> str:
180
+ return f"Bind({str(self)!r})"
181
+
182
+ def __eq__(self, other: object) -> bool:
183
+ if not isinstance(other, Bind):
184
+ return NotImplemented
185
+ return (self.kind, self.port, self.host, self.path) == (other.kind, other.port, other.host, other.path)
186
+
187
+ def __hash__(self) -> int:
188
+ return hash((self.kind, self.port, self.host, self.path))