Python stable · Mojo preview
Học CoAkka Runtime qua Python + Mojo
Python là hành trình package-manager hoàn chỉnh: Embedded trước, peer và data lanes sau. Mojo nằm cùng family học tập nhưng là source preview riêng qua packaged C shim; chưa có high-level Mojo API ổn định.
Beginner · 01 / 04
Cài wheel và nhận reply đầu tiên
Dùng CPython có GIL từ 3.11 trở lên. Gói 3.3.2 cài kèm gói native tương ứng. Trong ví dụ, import coakka_v2_connector.
python --versionmkdir coakka-python-demo
cd coakka-python-demo
python -m venv .venv
. .venv/bin/activate
python -m pip install --only-binary=:all: coakka-runtime-python==3.3.2Windows dùng .venv\Scripts\python.exe -m pip install --only-binary=:all: coakka-runtime-python==3.3.2. Luôn chạy python -m pip từ đúng interpreter.
from coakka_v2_connector import ConnectorStartSpec, RuntimeHost, local_route
target = "customers.accept"
start_spec = ConnectorStartSpec(
system_name="customer-app",
node_id="customer-app-1",
routes=[local_route(target)],
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
runtime.register_payload_handler(target, lambda payload: b"accepted-" + payload)
reply = runtime.ask_payload(
source="customer-api",
target=target,
payload=b"hello",
timeout_ms=2_000,
)
print(reply.decode("utf-8"))
python first_run.pyKết quả mong đợi
accepted-hello
ConnectorStartSpec- Intent startup của app-host; queue, network và Monitor bị bỏ trống để Core chọn default.
local_route(target)- Tạo route cùng process mà không bịa host/port.
with RuntimeHost.start(...)- Context manager giữ một owner và luôn đóng nó khi scope kết thúc.
ask_payload- Bytes-first request/reply; Core sở hữu framing và terminal matching.
Beginner · 02 / 04
Đặt tên cho việc cần làm
Target orders.quote là địa chỉ nghiệp vụ. Handler tính giá; caller chỉ biết target.
from coakka_v2_connector import ConnectorStartSpec, RuntimeHost, local_route
target = "orders.quote"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="orders-python-1",
routes=[local_route(target)],
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
runtime.register_payload_handler(
target,
lambda payload: str(int(payload) * 120_000).encode("utf-8"),
)
for quantity in (1, 2):
reply = runtime.ask_payload(
source="checkout",
target=target,
payload=str(quantity).encode("utf-8"),
timeout_ms=2_000,
)
print(f"quantity={quantity} quote={reply.decode('utf-8')} VND")
python quote.pyKết quả mong đợi
quantity=1 quote=120000 VND quantity=2 quote=240000 VND
Beginner · 03 / 04
Đọc deadletter có cấu trúc
Route miss sau admission là DeadletterError, không phải business response hay timeout. Branch theo reason code; không parse detail text.
from coakka_v2_connector import (
ConnectorStartSpec,
DeadletterError,
RuntimeHost,
local_route,
)
live_target = "orders.quote"
missing_target = "orders.missing"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="orders-python-1",
routes=[local_route(live_target)],
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
try:
runtime.ask_payload(
source="checkout",
target=missing_target,
payload=b"1",
timeout_ms=2_000,
)
except DeadletterError as error:
deadletter = error.deadletter
print(
f"deadletter reason={deadletter.reason} "
f"target={deadletter.original_envelope.target}"
)
python route_miss.pyKết quả mong đợi
deadletter reason=2 target=orders.missing
Phân biệt admission failure, Deadletter, response và timeout.
Beginner · 04 / 04
Để app sở hữu lifecycle
Tạo host ở composition root, truyền owner vào service cần gọi và không tạo runtime theo request.
from coakka_v2_connector import ConnectorStartSpec, RuntimeHost, local_route
def run_checkout(runtime: RuntimeHost) -> None:
reply = runtime.ask_payload(
source="checkout",
target="orders.quote",
payload=b"2",
timeout_ms=2_000,
)
print(f"checkout total={reply.decode('utf-8')} VND")
target = "orders.quote"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="orders-python-1",
routes=[local_route(target)],
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
runtime.register_payload_handler(
target,
lambda payload: str(int(payload) * 120_000).encode("utf-8"),
)
run_checkout(runtime)
python integration.pyKết quả mong đợi
checkout total=240000 VND
Advanced · 05 / 08
Chuyển handler sang peer, giữ nguyên target
Mở hai terminal. Service là NETWORK_NODE; caller là OUTBOUND_ONLY. Loopback chỉ minh hoạ hai process trên một máy; production thay bằng private DNS/IP.
from coakka_v2_connector import (
ConnectorStartSpec,
RuntimeHost,
RuntimeNetworkConfig,
local_route,
)
target = "orders.quote"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="quote-python-1",
routes=[local_route(target)],
network=RuntimeNetworkConfig.network_node(
bind_host="127.0.0.1",
bind_port=19_321,
advertise_host="127.0.0.1",
advertise_port=19_321,
),
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
runtime.register_payload_handler(
target,
lambda payload: str(int(payload) * 120_000).encode("utf-8"),
)
print("quote service ready on 127.0.0.1:19321")
input("Press Enter to stop...\n")
python quote_service.pyfrom coakka_v2_connector import (
ConnectorStartSpec,
EndpointSpec,
RouteSpec,
RouteStrategy,
RuntimeHost,
RuntimeNetworkConfig,
)
target = "orders.quote"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="checkout-python-1",
routes=[
RouteSpec(
target=target,
endpoints=[EndpointSpec(host="127.0.0.1", port=19_321)],
strategy=RouteStrategy.SINGLE_OWNER,
)
],
network=RuntimeNetworkConfig.outbound_only(),
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
reply = runtime.ask_payload(
source="checkout",
target=target,
payload=b"3",
timeout_ms=2_000,
)
print(f"order quote: {reply.decode('utf-8')} VND")
python checkout.pyKết quả mong đợi
order quote: 360000 VND
network_node- Bind là nơi listener mở; advertise là endpoint peer dùng.
outbound_only- Caller gọi peer mà không mở inbound listener.
RouteStrategy.SINGLE_OWNER- Một endpoint sở hữu target trong bài này; failover nhiều endpoint là kiến thức product Advanced.
Advanced · 06 / 08
Chuyển file bất biến bằng File Lane
File Lane là owner độc lập. Receiver cấp grant gắn exact owner; cả hai phía phải terminal thành công trước khi forget.
from pathlib import Path
from tempfile import TemporaryDirectory
from coakka_v2_connector import (
FileLane,
FileLaneConfig,
FileReceiveSpec,
FileTransferDirection,
LaneOwnerConfig,
)
def wait_terminal(lane: FileLane, transfer_id: str, direction: FileTransferDirection):
sequence = 0
while True:
snapshot = lane.wait_transfer(
transfer_id=transfer_id,
direction=direction,
after_update_sequence=sequence,
timeout_ms=5_000,
)
if snapshot.terminal:
return snapshot
sequence = snapshot.update_sequence
with TemporaryDirectory() as directory:
root = Path(directory)
source = root / "source.txt"
destination = root / "received.txt"
source.write_text("hello from File Lane", encoding="utf-8")
digest = FileLane.sha256(source)
with FileLane.open_owned(
config=FileLaneConfig(),
owner=LaneOwnerConfig(
owner_instance_id="receiver-python-1",
advertised_host="127.0.0.1",
),
) as receiver, FileLane.open() as sender:
transfer_id = "python-file-1"
grant = receiver.prepare_receive_grant(
FileReceiveSpec(
transfer_id=transfer_id,
authorization_token="file-token-1",
destination_path=destination,
expected_size=digest.size,
expected_sha256=digest.sha256,
)
)
sender.submit_send(grant.to_send_spec(source_path=source, timeout_ms=5_000))
sent = wait_terminal(sender, transfer_id, FileTransferDirection.SEND)
received = wait_terminal(receiver, transfer_id, FileTransferDirection.RECEIVE)
if not sent.completed or not received.completed:
raise RuntimeError("File Lane did not complete on both peers")
print(destination.read_text(encoding="utf-8"))
sender.forget(transfer_id, FileTransferDirection.SEND)
receiver.forget(transfer_id, FileTransferDirection.RECEIVE)
python file_lane.pyKết quả mong đợi
hello from File Lane
Advanced · 07 / 08
Gửi frame trực tiếp bằng Stream Lane
Callback source ghi vào borrowed destination; consumer phải copy trước khi callback kết thúc nếu muốn giữ data. Window giữ số byte in-flight có bound.
from coakka_v2_connector import (
LaneOwnerConfig,
StreamConsumerDecision,
StreamDirection,
StreamLane,
StreamLaneConfig,
StreamPublishSpec,
StreamSourceFrame,
StreamSourceSignal,
)
frames = [b"frame-one", b"frame-two"]
received: list[str] = []
def next_frame(destination: memoryview):
if not frames:
return StreamSourceSignal.END
frame = frames.pop(0)
destination[: len(frame)] = frame
return StreamSourceFrame(size=len(frame))
def consume_frame(data: memoryview, _metadata):
received.append(bytes(data).decode("utf-8"))
return StreamConsumerDecision.CONTINUE
def wait_terminal(lane: StreamLane, session_id: str, direction: StreamDirection):
sequence = 0
while True:
snapshot = lane.wait_session(
session_id=session_id,
direction=direction,
after_update_sequence=sequence,
timeout_ms=5_000,
)
if snapshot.terminal:
return snapshot
sequence = snapshot.update_sequence
with StreamLane.open_owned(
config=StreamLaneConfig(),
owner=LaneOwnerConfig(
owner_instance_id="publisher-python-1",
advertised_host="127.0.0.1",
),
) as publisher, StreamLane.open() as subscriber:
session_id = "python-stream-1"
grant = publisher.prepare_publish_grant(
StreamPublishSpec(
session_id=session_id,
authorization_token="stream-token-1",
format_id=1,
max_frame_bytes=1_024,
source=next_frame,
)
)
subscriber.subscribe(
grant.to_subscribe_spec(
initial_window_bytes=4_096,
consumer=consume_frame,
timeout_ms=5_000,
)
)
published = wait_terminal(publisher, session_id, StreamDirection.PUBLISH)
subscribed = wait_terminal(subscriber, session_id, StreamDirection.SUBSCRIBE)
if not published.completed or not subscribed.completed:
raise RuntimeError("Stream Lane did not end successfully on both peers")
print(", ".join(received))
publisher.forget(session_id, StreamDirection.PUBLISH)
subscriber.forget(session_id, StreamDirection.SUBSCRIBE)
python stream_lane.pyKết quả mong đợi
frame-one, frame-two
Advanced · 08 / 08
Bật Monitor trước startup
Monitor mặc định OFF. enable_monitor=True là intent; monitor_is_enabled() và snapshot là facts do Core trả về.
from coakka_v2_connector import ConnectorStartSpec, RuntimeHost, local_route
target = "orders.quote"
start_spec = ConnectorStartSpec(
system_name="orders",
node_id="monitor-python-1",
routes=[local_route(target)],
enable_monitor=True,
)
with RuntimeHost.start(start_spec=start_spec) as runtime:
snapshot = runtime.await_next_monitor(timeout_ms=1_000)
if snapshot is None:
raise RuntimeError("expected the startup Monitor signal")
runtime.register_payload_handler(target, lambda payload: payload)
runtime.ask_payload(
source="checkout",
target=target,
payload=b"signal",
timeout_ms=2_000,
)
print(f"monitor enabled={str(runtime.monitor_is_enabled()).lower()}")
print(f"state={snapshot.health['runtimeState']} signal={snapshot.signal_count}")
python monitoring.pyKết quả đã kiểm chứng
monitor enabled=true state=1 signal=1
Preview · 09
Chạy Mojo source preview, không giả API ổn định
Mojo 3.3.1 preview ghim toolchain 1.0.0b2.dev2026052115. Thin Mojo executable gọi packaged C shim; shim sở hữu toàn bộ runtime lifecycle và kiểm tra request/reply, cancellation và route miss.
curl -fL -o coakka-runtime-mojo-3.3.1-source.tar.gz \
'https://raw.githubusercontent.com/phuong-tran/coakka-publish/22d885f240dd9c458249fe93854a8a7ec8ba0b4a/coakka-runtime/mojo/releases/3.3.1%2B16bdd692faf918d1a959c073ad20318392659f4b/coakka-runtime-mojo-3.3.1-source.tar.gz'
printf '%s %s\n' \
'a9b1a9cc78086d92d81294f7c1efa7e42c510f81df115d3830545bf5f143e5c1' \
'coakka-runtime-mojo-3.3.1-source.tar.gz' | shasum -a 256 -c -
tar -xzf coakka-runtime-mojo-3.3.1-source.tar.gzfrom std.ffi import OwnedDLHandle, c_int
from std.sys import argv
# Mojo's direct native-call surface is still evolving. The packaged C shim
# owns the complete CoAkka Runtime lifecycle; this file is not a stable
# high-level Mojo application API.
def main() raises:
var args = argv()
if len(args) != 2:
print("usage: mojo runtime_connector_smoke.mojo <connector-shim-library>")
raise Error("missing connector shim library path")
var lib = OwnedDLHandle(String(args[1]))
var status = lib.call["coakka_mojo_runtime_connector_smoke", c_int](0)
if status != 0:
raise Error("coakka_mojo_runtime_connector_smoke failed")
mkdir -p coakka-mojo-work
cd coakka-runtime-mojo-3.3.1-source
export COAKKA_CONNECTOR_WORK_ROOT="$(cd .. && pwd)/coakka-mojo-work"
if [ "$(uname -s)" = Darwin ]; then
export SDKROOT="$(xcrun --sdk macosx --show-sdk-path)"
export MACOSX_DEPLOYMENT_TARGET=13.0
fi
bash scripts/verify-native-payload.sh
bash scripts/smoke.shExecution evidence hiện có trên macOS ARM64 và Raspberry Pi 5 Linux ARM64. Năm native images trong archive là payload inventory, không tự chứng minh Mojo compiler support trên mọi target.