Study · Python · exact wheel 2.3.2
Natural Python, one shared HTTP contract
Install one ABI3 wheel with its native payload, write ordinary Python handlers, and let CoAkka HTTP Runtime own transport, bounds and effective state.
Beginner · 01 / 04
Create an environment, then install the exact wheel
python3 -m venv .venv
.venv/bin/python -m pip install --only-binary=:all: coakka-http-runtime-python==2.3.2- Interpreter
- Standard CPython 3.11+; PyPy and free-threaded builds are outside this support claim.
--only-binary=:all:- Fail clearly when no matching wheel exists instead of silently building a different artifact.
- ABI3
- The wheel carries the
cp311-abi3tag, so newer CPython versions can use the same stable-ABI build. - Native payload
- It is bundled in the wheel; Study does not require a separate native SDK or compiler.
On Windows use py -3 -m venv .venv, then run .venv\Scripts\python.exe -m pip .... Always install and run with the same interpreter and architecture.
Beginner · 02 / 04
A complete service for your IDE
Save the complete file below as server.py:
from coakka_http import Builder, Request, Response
def hello(request: Request) -> Response:
name = request.path_parameters[0].encoded_value
return Response.text(f"hello {name}", status=200)
def main() -> None:
service = (
Builder()
.listen("127.0.0.1", 0)
.get("/hello/{name}", hello)
.start()
)
with service:
print(f"http://127.0.0.1:{service.port}/hello/Ada", flush=True)
input("Press Enter to close. ")
if __name__ == "__main__":
main()
.venv/bin/python server.pyOpen the printed URL, or run curl -i http://127.0.0.1:49321/hello/Ada. Expect 200 hello Ada. Press Enter so the context manager closes the service.
127.0.0.1- Study listens on loopback only; it does not expose the service to a network.
0- The OS selects a free port; read
service.portafter start. with service- The service is the owner. Leaving the block performs checked close instead of relying on garbage collection.
Beginner · 03 / 04
Requests and responses are copied Python values
name = request.path_parameters[0].encoded_value
return Response.text(f"hello {name}", status=200)
path_parameters- Preserves route-capture order;
encoded_valueremains percent-encoded. query_parameters- Preserves order, duplicates, and missing-versus-empty values.
headers.get(...)- Names are case-insensitive; use ordered entries when duplicates matter.
request.body- Buffered bytes within the configured limit; large uploads move to
post_stream. Response.text- The app chooses body and status. JSON and domain validation remain application-owned.
The adapter copies native views during the call; no borrowed pointer escapes into Python. You may retain those values under Python memory rules, but application queues and caches still need bounds.
Beginner · 04 / 04
Outbound still matches call identity and terminal reason
Keep the server running and save this file as outbound.py:
from __future__ import annotations
import sys
from coakka_http import (
Builder,
OutboundEndpoint,
OutboundReason,
OutboundRequest,
OutboundTarget,
)
def main() -> None:
port = int(sys.argv[1])
endpoint = OutboundEndpoint(
node_id="loopback",
connect_host="127.0.0.1",
connect_port=port,
http_authority=f"127.0.0.1:{port}",
)
target = OutboundTarget(name="hello", generation=1, endpoints=(endpoint,))
with Builder().outbound_target(target).start() as service:
call = service.outbound_submit(
OutboundRequest(
"hello",
"GET",
"/hello/Ada",
timeout_ms=3_000,
)
)
terminal = service.take_outbound(5_000)
if terminal is None:
raise TimeoutError("No outbound terminal within five seconds")
if terminal.call != call:
raise RuntimeError("Outbound terminal belongs to another call")
if terminal.reason is not OutboundReason.RESPONSE:
raise RuntimeError(f"Outbound ended with {terminal.reason.name}")
print(terminal.response_status, terminal.response_body.decode("utf-8"))
if __name__ == "__main__":
main()
SERVER_PORT=49321
.venv/bin/python outbound.py "$SERVER_PORT"Replace 49321 with the real port. Expect 200 hello Ada. The five-second reader wait does not replace the three-second call deadline; HTTP 404 is still RESPONSE, not a transport failure.
Advanced · 05
Learn one capability at a time, then combine them
Each first file opens one endpoint so the lesson stays on one contract. Use the official 2.3.2 wheel installed in episode 1.
01 · File deliveryAuthority, relative path and limits; the Runtime selects sendfile when eligible.
from pathlib import Path
from tempfile import TemporaryDirectory
from coakka_http import Builder, FileAuthority, FileResponse
def main() -> None:
with TemporaryDirectory(prefix="coakka-http-file-") as root:
Path(root, "manual.txt").write_text("CoAkka file delivery\n")
service = (
Builder()
.listen("127.0.0.1", 0)
.file_authority(
FileAuthority(
authority_id=1,
root_path=root,
max_file_bytes=1024,
max_active_files=4,
)
)
.get("/download", lambda _request: FileResponse(1, "/manual.txt"))
.start()
)
with service:
print(f"curl http://127.0.0.1:{service.port}/download")
input("Press Enter to close. ")
if __name__ == "__main__":
main()
.venv/bin/python file.py02 · Server-Sent EventsEmit two one-way events, then finish the stream.
from coakka_http import Builder, ServerSentEventsResponse, SseEvent
def events(_request):
def produce(writer) -> None:
writer.write(
SseEvent(b"ready", event_type=b"state", id=b"1", retry_ms=1000)
)
writer.write(SseEvent(b"done"))
return ServerSentEventsResponse(produce)
def main() -> None:
service = (
Builder()
.listen("127.0.0.1", 0)
.get("/events", events)
.start()
)
with service:
print(f"curl -N http://127.0.0.1:{service.port}/events")
input("Press Enter to close. ")
if __name__ == "__main__":
main()
.venv/bin/python sse.py03 · WebSocketGreeting and text echo in one bidirectional session.
from coakka_http import Builder, WebSocketEventKind, WebSocketResponse
def socket(_request):
def handle(session, event) -> None:
if event.kind is WebSocketEventKind.OPEN:
session.send_text("ready")
elif event.kind is WebSocketEventKind.TEXT:
session.send_text(f"echo: {event.data.decode()}")
return WebSocketResponse(handle, subprotocol="coakka.demo")
def main() -> None:
service = (
Builder()
.listen("127.0.0.1", 0)
.websocket("/socket", socket)
.start()
)
with service:
print(
"new WebSocket("
f"'ws://127.0.0.1:{service.port}/socket', 'coakka.demo')"
)
input("Press Enter to close. ")
if __name__ == "__main__":
main()
.venv/bin/python websocket.py04 · Combine them in one serviceAn optional integration exercise after the three contracts are clear.
from pathlib import Path
from tempfile import TemporaryDirectory
from coakka_http import (
Builder,
FileAuthority,
FileResponse,
ServerSentEventsResponse,
SseEvent,
WebSocketEventKind,
WebSocketResponse,
)
def events(_request):
def produce(writer) -> None:
writer.write(
SseEvent(b"ready", event_type=b"state", id=b"1", retry_ms=1000)
)
writer.write(SseEvent(b"done"))
return ServerSentEventsResponse(produce)
def socket(_request):
def handle(session, event) -> None:
if event.kind is WebSocketEventKind.OPEN:
session.send_text("ready")
elif event.kind is WebSocketEventKind.TEXT:
session.send_text(f"echo: {event.data.decode()}")
return WebSocketResponse(handle, subprotocol="coakka.demo")
def main() -> None:
with TemporaryDirectory(prefix="coakka-http-advanced-") as root:
Path(root, "manual.txt").write_text("CoAkka file delivery\n")
service = (
Builder()
.listen("127.0.0.1", 0)
.file_authority(
FileAuthority(
authority_id=1,
root_path=root,
max_file_bytes=1024,
max_active_files=4,
)
)
.get("/download", lambda _request: FileResponse(1, "/manual.txt"))
.get("/events", events)
.websocket("/socket", socket)
.start()
)
with service:
print(f"file: curl http://127.0.0.1:{service.port}/download")
print(f"SSE: curl -N http://127.0.0.1:{service.port}/events")
print(
"WS: new WebSocket("
f"'ws://127.0.0.1:{service.port}/socket', 'coakka.demo')"
)
input("Press Enter to close. ")
if __name__ == "__main__":
main()
.venv/bin/python advanced.pyNever retain a writer or session beyond its callback. Look up parameters, failures and monitoring.
Find all feature guides · Try gzip · Run the upload labs · Resume a large upload
Advanced · 06
Live routes preserve generation and binding revision
| Operation | Python API | Invariant |
|---|---|---|
| Snapshot | service.routes | A Core-issued coherent cut, not builder echo. |
| Prepare | prepare_handler | Prepare the callable before publication. |
| Rebind | rebind_handler | Expected generation/revision; admitted requests keep the old handler. |
| Publish | publish_routes | Replace one complete structural generation, never a loose patch. |
| TLS rotation | Typed reload operation | Observe applied/rejected state; never infer it from a file timestamp. |
Advanced · 07
Read effective truth; enable Monitor only when needed
runtime_info()- Protocol, provider and capability state that Core actually accepted.
effective_limits()- Resolved bounds; never reconstruct them from builder input.
- Health/liveness
- Direct health and a bounded fresh probe work independently of Monitor.
- Monitor
MonitorOptionsreserves storage before start; pull copied snapshots/events with cursor and loss facts.- Low-level
Runtime - One immutable
RuntimeConfig, typed copied events and one reader per lane; use it when you must own dispatch.
Advanced · 08
Failure, close and Python quick reference
- Startup
Builderis single-use; invalid configuration or providers fail before ready.- Native failure
NativeErrorcarries a stable numeric status and bounded diagnostic; do not parse text to change semantics.- Handler/producer
- Keep application exceptions distinct from pressure, timeout and cancellation, and read service error evidence.
- Close
- Wakes readers, joins connector work, then destroys the native owner. If close raises, retain the service owner for a safe retry.
- Evidence
- Wheel hash/tag, interpreter path/version/architecture, loaded module/native path, runtime info/limits, and terminal/loss facts.
- Use CPython 3.11+ with the wheel's architecture.
- Install and run in one virtual environment; do not mix ambient
PYTHONPATH. - Never retain a callback-scoped writer or session.
- Keep one reader for each blocking lane.
- Never drop the service while close is incomplete.