Study · Python · exact wheel 2.3.2
Python tự nhiên, HTTP contract dùng chung
Cài một ABI3 wheel đã kèm native payload, viết handler Python bình thường và để CoAkka HTTP Runtime sở hữu transport, bounds cùng effective state.
Beginner · 01 / 04
Tạo môi trường rồi cài đúng 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 và free-threaded build không nằm trong support claim này.
--only-binary=:all:- Fail rõ nếu không có wheel khớp thay vì âm thầm build một artifact khác.
- ABI3
- Wheel mang tag
cp311-abi3, nên CPython mới hơn có thể dùng cùng stable-ABI build. - Native payload
- Đã nằm trong wheel; không cài native SDK hoặc compiler riêng cho Study.
Windows dùng py -3 -m venv .venv, rồi chạy .venv\Scripts\python.exe -m pip .... Luôn cài và chạy bằng cùng interpreter/architecture.
Beginner · 02 / 04
Một service copy được vào IDE
Lưu toàn bộ file dưới thành 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.pyMở URL chương trình in ra, hoặc chạy curl -i http://127.0.0.1:49321/hello/Ada. Kết quả là 200 hello Ada. Nhấn Enter để context manager close service.
127.0.0.1- Study chỉ listen loopback, chưa mở service ra network.
0- OS chọn một port trống; luôn dùng
service.portsau start. with service- Service là owner. Rời block sẽ chạy checked close thay vì dựa vào garbage collection.
Beginner · 03 / 04
Request và response là Python values đã copy
name = request.path_parameters[0].encoded_value
return Response.text(f"hello {name}", status=200)
path_parameters- Giữ thứ tự capture của route;
encoded_valuevẫn percent-encoded. query_parameters- Giữ order, duplicate và khác biệt giữa thiếu value với value rỗng.
headers.get(...)- Lookup tên case-insensitive; dùng ordered entries khi duplicate có ý nghĩa.
request.body- Buffered bytes trong configured limit; upload lớn chuyển sang
post_stream. Response.text- App chọn body/status. JSON/domain validation vẫn thuộc application.
Adapter copy native views trong call; không có borrowed pointer thoát sang Python. Vì vậy value có thể giữ lại theo luật memory của Python, nhưng queue/cache của app vẫn phải có bound.
Beginner · 04 / 04
Outbound vẫn match call identity và terminal reason
Giữ server đang chạy, lưu file sau thành 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"Thay 49321 bằng port thật. Kết quả 200 hello Ada. Reader wait 5 giây không thay thế call deadline 3 giây; HTTP 404 vẫn là RESPONSE, không phải transport failure.
Advanced · 05
Học từng capability trước khi kết hợp
Mỗi file đầu tiên chỉ mở một endpoint để tập trung vào đúng contract. Dùng wheel chính thức 2.3.2 đã cài ở tập 1.
01 · File deliveryAuthority, relative path và giới hạn; Runtime tự chọn sendfile khi đủ điều kiện.
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 EventsPhát hai event một chiều rồi kết thúc 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 và text echo trong một session hai chiều.
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 · Kết hợp trong một serviceBài tích hợp tùy chọn sau khi ba contract riêng đã rõ.
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.pyKhông giữ writer hoặc session ngoài callback. Tra tham số, lỗi và monitor.
Tra cứu toàn bộ tính năng · Thử gzip · Chạy bài upload · Tiếp tục tải tệp lớn lên
Advanced · 06
Live routes giữ generation và binding revision
| Việc | Python API | Invariant |
|---|---|---|
| Snapshot | service.routes | Core-issued coherent cut, không builder echo. |
| Prepare | prepare_handler | Chuẩn bị callable trước khi publish. |
| Rebind | rebind_handler | Expected generation/revision; request đã admit giữ handler cũ. |
| Publish | publish_routes | Thay một complete structural generation, không patch lẻ. |
| TLS rotation | Typed reload operation | Quan sát applied/rejected state; không suy từ file timestamp. |
Advanced · 07
Đọc effective truth; chỉ bật Monitor khi cần
runtime_info()- Protocol/provider/capability state Core thật sự chấp nhận.
effective_limits()- Resolved bounds; không tự dựng lại từ builder input.
- Health/liveness
- Direct health và bounded fresh probe chạy độc lập với Monitor.
- Monitor
MonitorOptionsreserve storage trước start; pull copied snapshots/events cùng cursor/loss facts.- Low-level
Runtime - Một immutable
RuntimeConfig, typed copied events, one reader mỗi lane; dùng khi cần tự sở hữu dispatch.
Advanced · 08
Failure, close và Python quick reference
- Startup
Buildersingle-use; invalid config/provider fail trước ready.- Native failure
NativeErrorcó stable numeric status và bounded diagnostic; không parse text để đổi semantics.- Handler/producer
- Giữ application exception tách pressure/timeout/cancellation và đọc service error evidence.
- Close
- Wakes readers, joins connector work rồi destroy native owner. Nếu close raise, giữ service owner sống để retry an toàn.
- Evidence
- Wheel hash/tag, interpreter path/version/arch, loaded module/native path, runtime info/limits và terminal/loss facts.
- Dùng CPython 3.11+ cùng architecture với wheel.
- Cài và chạy cùng một virtualenv; không trộn ambient
PYTHONPATH. - Không giữ callback-scoped writer/session.
- Mỗi blocking lane chỉ một reader.
- Không drop service khi close chưa hoàn tất.