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.

Kiểm tra Python
python --version
Tạo môi trường và cài package
mkdir 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.2

Windows 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.

first_run.py
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"))
Terminal
python first_run.py

Kế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.

Xem wheel PyPI 3.3.2 (tuỳ chọn)

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.

quote.py
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")
Terminal
python quote.py

Kế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.

route_miss.py
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}"
        )
Terminal
python route_miss.py

Kế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.

integration.py
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)
Terminal
python integration.py

Kế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.

quote_service.py
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")
Terminal 1
python quote_service.py
checkout.py
from 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")
Terminal 2
python checkout.py

Kế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.

Tra distributed, failover và retry.

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.

file_lane.py
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)
Terminal
python file_lane.py

Kết quả mong đợi

hello from File Lane

Tra integrity, resume, pressure và terminal law.

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.

stream_lane.py
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)
Terminal
python stream_lane.py

Kết quả mong đợi

frame-one, frame-two

Tra flow control và pressure.

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ề.

monitoring.py
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}")
Terminal
python monitoring.py

Kết quả đã kiểm chứng

monitor enabled=true
state=1 signal=1

Chạy configuration lab · Tra operations và evidence

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.

Terminal · tải và kiểm tra archive
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.gz
runtime_connector_smoke.mojo
from 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")
Terminal · exact archive smoke
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.sh

Execution 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.