Metadata-Version: 2.4
Name: mini-aiohttp
Version: 0.2.0
Summary: A lightweight asynchronous HTTP/1.1 client and server with streaming, proxies, middleware, and security features
License-Expression: MIT
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Requires-Dist: pytest-asyncio<1.0,>=0.21; extra == "test"
Dynamic: license-file

# mini-aiohttp

**mini-aiohttp 0.2.0** is a lightweight asynchronous HTTP/1.1 client and server built on Python's standard library and asyncio. It has no mandatory runtime dependencies and supports Python 3.9+.

## Features

### HTTP client
- Async HTTP/1.1 requests with keep-alive connection pooling and per-host concurrency limits.
- Redirect handling with cross-origin credential stripping.
- Bounded retries for idempotent methods only; streaming request bodies are never replayed.
- Cookie jar with host/domain, path and Secure matching.
- Streaming response downloads and async-iterable uploads using chunked transfer encoding.
- Multipart form and file uploads.
- HTTP and SOCKS5/SOCKS5h proxy support for HTTP targets.
- DNS cache, configurable timeouts, TLS context, request/response hooks.
- Bounded response sizes.

### HTTP server
- Async routing, path parameters and middleware on successful, error and static-file responses.
- HTTP/1.1 keep-alive, bounded request bodies and chunked request decoding.
- HTTPS via a caller-provided ssl.SSLContext.
- Static file serving with resolved-path traversal protection and size limits.
- Chunked streaming responses using Response.stream().
- Graceful shutdown and connection caps.
- Lightweight runtime counters through Server.stats.

### Security
- Header validation and request framing checks.
- CORS, security headers, token-bucket rate limiting and IP/CIDR policy middleware.
- Secure cookie helper and JSON request validation.
- Safe redirect behavior and bounded parsing.

## Installation

~~~bash
pip install mini-aiohttp
pip install "mini-aiohttp[test]"  # test extras when installing from source
~~~

## Quick start

~~~python
import asyncio
from mini_aiohttp import ClientSession, Response, Server

app = Server()

@app.route("/")
async def index(req):
    return Response.json({"message": "hello"})

@app.route("/echo", method="POST")
async def echo(req):
    return Response(200, req.body)

async def main():
    await app.start("127.0.0.1", 8080)
    try:
        async with ClientSession() as session:
            response = await session.get("http://127.0.0.1:8080/")
            print(response.status, response.json())
    finally:
        await app.close()

asyncio.run(main())
~~~

## Streaming response (including SSE)

~~~python
import asyncio
from mini_aiohttp import Response, Server

app = Server()

@app.route("/events")
async def events(req):
    async def generate():
        for number in range(3):
            yield f"data: {number}\n\n"
            await asyncio.sleep(1)

    return Response.stream(
        generate(),
        headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"},
    )

asyncio.run(app.serve_forever("127.0.0.1", 8080))
~~~

The server sends streamed bodies as HTTP/1.1 chunked transfer encoding. If the producer raises after response headers have been sent, the connection is closed; an HTTP error response can no longer be substituted at that point.

## Client streaming

~~~python
async def upload_chunks():
    yield b"part one"
    yield b"part two"

async with ClientSession() as session:
    response = await session.post(
        "http://127.0.0.1:8080/echo",
        data=upload_chunks(),
    )
    print(response.status)
~~~

## Runtime stats

~~~python
print(app.stats)
# {
#   "active_connections": 0,
#   "total_connections": 1,
#   "total_requests": 2,
#   "status_counts": {200: 1, 404: 1},
#   "uptime_requests_per_connection": 2.0
# }
~~~

Counters are process-local snapshots, not a distributed metrics backend. They do not expose CPU or memory usage.

## Testing and building

~~~bash
python -m pip install -e ".[test]"
python -m pytest -v
python -m pip install build twine
python -m build
python -m twine check dist/*
~~~

GitHub Actions runs the test suite on Python 3.9, 3.10, 3.11, 3.12 and 3.13, and checks source/wheel distributions.

## Current protocol boundaries

- HTTP/1.1 only; HTTP/2 and HTTP/3 are not implemented.
- WebSockets are not implemented.
- HTTPS through HTTP/SOCKS proxies is not implemented.
- SOCKS proxy support is for HTTP targets; use a direct TLS connection for HTTPS.
- Streaming responses require an async iterable.
- No automatic multi-process worker manager is included. reuse_port=True can be used where supported.
- Performance depends on OS limits, hardware, network conditions and application handlers. Run benchmarks on the target deployment; no fixed connection/throughput guarantee is made.

## License

MIT
