Skip to content
Open
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
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ repos:
hooks:
- id: mypy
name: Mypy
entry: uv run --no-sync mypy src
entry: uv run --no-sync mypy src tests
language: system
types: [python]
pass_filenames: false
Expand Down
22 changes: 22 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,25 @@ dev = [
[build-system]
requires = ["uv_build>=0.13.0,<0.14.0"]
build-backend = "uv_build"

[tool.mypy]
strict = true

[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false
check_untyped_defs = true

[[tool.mypy.overrides]]
module = [
"hip.client.*",
"hip.server.*",
"hip.parsers.*",
"tests.test_client",
"tests.test_server",
"tests.test_pool",
"tests.test_network",
"tests.test_parsers",
"tests.parsers.*",
]
Comment on lines +45 to +55

@lovelydinosaur lovelydinosaur Dec 2, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the plan that we would incrementally drop these overrides?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes

ignore_errors = true
2 changes: 1 addition & 1 deletion scripts/check
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/bin/sh -e

uv run --no-sync mypy src
uv run --no-sync mypy src tests
46 changes: 27 additions & 19 deletions src/hip/backends/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def close(self) -> None:
pass
self._socket.close()

def __repr__(self):
def __repr__(self) -> str:
description = ""
description += " TLS" if self._is_tls else ""
description += " CLOSED" if self._is_closed else ""
Expand All @@ -69,7 +69,7 @@ def __exit__(
exc_type: type[BaseException] | None = None,
exc_value: BaseException | None = None,
traceback: types.TracebackType | None = None,
):
) -> None:
self.close()


Expand All @@ -80,11 +80,11 @@ def __init__(self, sock: socket.socket, address: tuple[str, int]) -> None:
self._is_closed = False

@property
def host(self):
def host(self) -> str:
return self._address[0]

@property
def port(self):
def port(self) -> int:
return self._address[1]

def accept(self) -> NetworkStream | None:
Expand All @@ -99,7 +99,7 @@ def accept(self) -> NetworkStream | None:
return NetworkStream(sock, address)
return None

def close(self):
def close(self) -> None:
self._is_closed = True
self._server_socket.close()

Expand All @@ -111,7 +111,7 @@ def __exit__(
exc_type: type[BaseException] | None = None,
exc_value: BaseException | None = None,
traceback: types.TracebackType | None = None,
):
) -> None:
self.close()


Expand All @@ -122,36 +122,44 @@ def __init__(
self.listener = listener
self.handler = handler
self._max_workers = 10
self._executor = None
self._thread = None
self._executor: concurrent.futures.ThreadPoolExecutor | None = None
self._streams: list[NetworkStream] = []

@property
def host(self):
def host(self) -> str:
return self.listener.host

@property
def port(self):
def port(self) -> int:
return self.listener.port

def __enter__(self):
def __enter__(self) -> typing.Self:
self._executor = concurrent.futures.ThreadPoolExecutor(
max_workers=self._max_workers
)
self._executor.submit(self._serve)
return self

def __exit__(self, exc_type, exc_val, exc_tb):
def __exit__(
self,
exc_type: type[BaseException] | None = None,
exc_value: BaseException | None = None,
traceback: types.TracebackType | None = None,
) -> None:
executor = self._executor
assert executor is not None
for stream in self._streams:
stream.close()
self.listener.close()
self._executor.shutdown(wait=True)
executor.shutdown(wait=True)

def _serve(self):
def _serve(self) -> None:
executor = self._executor
assert executor is not None
while stream := self.listener.accept():
self._executor.submit(self._handler, stream)
executor.submit(self._handler, stream)

def _handler(self, stream):
def _handler(self, stream: NetworkStream) -> None:
try:
self._streams.append(stream)
self.handler(stream)
Expand All @@ -161,7 +169,7 @@ def _handler(self, stream):


class NetworkBackend:
def __init__(self, ssl_ctx: ssl.SSLContext | None = None):
def __init__(self, ssl_ctx: ssl.SSLContext | None = None) -> None:
self._ssl_ctx = self.create_default_context() if ssl_ctx is None else ssl_ctx

def create_default_context(self) -> ssl.SSLContext:
Expand Down Expand Up @@ -205,7 +213,7 @@ def serve(
listener = self.listen(host, port)
return NetworkServer(listener, handler)

def __repr__(self):
def __repr__(self) -> str:
return "<NetworkBackend [threaded]>"


Expand Down Expand Up @@ -250,7 +258,7 @@ def get_current_timeout() -> float | None:
return remaining


def sleep(dur: float):
def sleep(dur: float) -> None:
"""
A `sleep()` implementation that is aware of the current timeout context.
"""
Expand Down
4 changes: 3 additions & 1 deletion src/hip/backends/trio.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,9 @@ async def __aexit__(
) -> bool | None:
self._nursery.cancel_scope.cancel()
try:
return await self._nursery_context.__aexit__(exc_type, exc_value, traceback)
return await self._nursery_context.__aexit__( # type: ignore[no-any-return]
exc_type, exc_value, traceback
)
finally:
with trio.CancelScope(shield=True):
for listener in self._listeners:
Expand Down
8 changes: 4 additions & 4 deletions src/hip/core/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def headers(self) -> Headers:
def parse(self, stream: Stream) -> "Content":
raise NotImplementedError()

def __bytes__(self):
def __bytes__(self) -> bytes:
raise TypeError(
f"Content {self.__class__.__name__} does not support a bytes interface."
)
Expand Down Expand Up @@ -70,7 +70,7 @@ def value(self) -> typing.Any:

# dict and list style accessors, eg. for casting.
def keys(self) -> typing.KeysView[str]:
return self._data.keys()
return typing.cast(typing.KeysView[str], self._data.keys())

def __len__(self) -> int:
return len(self._data)
Expand All @@ -81,8 +81,8 @@ def __getitem__(self, key: typing.Any) -> typing.Any:
# Built-ins.
def __eq__(self, other: object) -> bool:
if isinstance(other, JSON):
return self._data == other._data
return self._data == other
return bool(self._data == other._data)
return bool(self._data == other)

def __str__(self) -> str:
return self._content.decode("utf-8")
Expand Down
10 changes: 5 additions & 5 deletions src/hip/core/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@


class Method:
def __init__(self, method: str, standard=True):
def __init__(self, method: str, standard: bool = True) -> None:
if standard:
method = method.upper()
if method not in STANDARD_METHODS:
Expand All @@ -28,7 +28,7 @@ def __init__(self, method: str, standard=True):
def has_body(self) -> bool:
return self._method in ("POST", "PUT", "PATCH")

def __eq__(self, other) -> bool:
def __eq__(self, other: object) -> bool:
return str(self) == str(other)

def __bytes__(self) -> bytes:
Expand All @@ -37,7 +37,7 @@ def __bytes__(self) -> bytes:
def __str__(self) -> str:
return self._method

def __repr__(self):
def __repr__(self) -> str:
return f"<Method {self._method}>"


Expand All @@ -48,7 +48,7 @@ def __init__(
url: URL | str,
headers: Headers | dict[str, str] | None = None,
content: Content | bytes | None = None,
):
) -> None:
self.method = Method(method) if not isinstance(method, Method) else method
self.url = URL(url) if not isinstance(url, URL) else url
self.headers = Headers(headers) if not isinstance(headers, Headers) else headers
Expand Down Expand Up @@ -79,5 +79,5 @@ def __init__(
def body(self) -> bytes:
return bytes(self.content)

def __repr__(self):
def __repr__(self) -> str:
return f"<Request [{self.method} {str(self.url)!r}]>"
10 changes: 5 additions & 5 deletions src/hip/core/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class StatusCode:
511: "Network Authentication Required",
}

def __init__(self, status_code: int):
def __init__(self, status_code: int) -> None:
if status_code < 100 or status_code > 999:
raise ValueError(f"Invalid status code {status_code!r}")
self.value = status_code
Expand Down Expand Up @@ -119,8 +119,8 @@ def has_body(self) -> bool:
def as_tuple(self) -> tuple[int, bytes]:
return (self.value, self.reason_phrase.encode("ascii"))

def __eq__(self, other) -> bool:
return int(self) == int(other)
def __eq__(self, other: object) -> bool:
return bool(int(self) == int(other)) # type: ignore[call-overload]

def __int__(self) -> int:
return self.value
Expand All @@ -139,7 +139,7 @@ def __init__(
*,
headers: Headers | dict[str, str] | None = None,
content: Content | bytes | None = None,
):
) -> None:
self.status_code = (
StatusCode(status_code)
if not isinstance(status_code, StatusCode)
Expand Down Expand Up @@ -169,5 +169,5 @@ def __init__(
def body(self) -> bytes:
return bytes(self.content)

def __repr__(self):
def __repr__(self) -> str:
return f"<Response [{self.status_code}]>"
20 changes: 12 additions & 8 deletions src/hip/core/streams.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import io
import os
import types
import typing

__all__ = ["Stream"]

Expand All @@ -15,20 +16,20 @@ def write(self, data: bytes) -> None:
def close(self) -> None:
raise NotImplementedError()

def __enter__(self):
def __enter__(self) -> typing.Self:
return self

def __exit__(
self,
exc_type: type[BaseException] | None = None,
exc_value: BaseException | None = None,
traceback: types.TracebackType | None = None,
):
) -> None:
self.close()


class ByteStream(Stream):
def __init__(self, data: bytes = b""):
def __init__(self, data: bytes = b"") -> None:
self._buffer = io.BytesIO(data)
self._size = len(data)

Expand All @@ -40,7 +41,7 @@ def close(self) -> None:


class FileStream(Stream):
def __init__(self, fileobj):
def __init__(self, fileobj: typing.BinaryIO) -> None:
self._fileobj = fileobj

def read(self, size: int = -1) -> bytes:
Expand All @@ -52,19 +53,22 @@ def close(self) -> None:

class MultiPartStream(Stream):
def __init__(
self, form: list[tuple[str, str]], files: list[tuple[str, str]], boundary=""
):
self,
form: list[tuple[str, str]],
files: list[tuple[str, str]],
boundary: str = "",
) -> None:
self._form = list(form)
self._files = list(files)
self._boundary = boundary or os.urandom(16).hex()
# Mutable state...
self._form_progress = list(self._form)
self._files_progress = list(self._files)
self._fileobj: io.IOBase | None = None
self._fileobj: typing.BinaryIO | None = None
self._complete = False
self._buffer = io.BytesIO()

def read(self, size=-1) -> bytes:
def read(self, size: int = -1) -> bytes:
sections = []
length = 0

Expand Down
Loading
Loading