"""Offline Rust semantic verifier for Chapter 29: Async/Await (Future lazy polling, asyncio tasks, .await?, async mpsc)."""
import asyncio
import json
from pathlib import Path
import tempfile
class PollCounterFuture:
"""Models a Rust Future returning Poll::Pending until polled `ticks` times, then Poll::Ready(value)."""
def __init__(self, ticks: int, value: int) -> None:
self.remaining = ticks
self.value = value
self.poll_count = 0
def poll(self) -> tuple[str, int | None]:
self.poll_count += 1
if self.remaining > 0:
self.remaining -= 1
return ("Pending", None)
return ("Ready", self.value)
async def async_task() -> int:
await asyncio.sleep(0)
return 42
async def execute_async_task(log: list[str]) -> int:
res = await async_task()
log.append(f"Async task result: {res}")
return res
async def hello() -> str:
return "Hello, world!"
async def add(a: int, b: int) -> int:
return a + b
async def mock_fetch_url(url: str) -> tuple[str, str]:
await asyncio.sleep(0)
if url.startswith("https://offline.local/posts/1"):
return ("Ok", '{"id": 1, "title": "offline-post"}')
return ("Err", f"unrecognized offline route: {url}")
async def async_error_propagation(url: str) -> tuple[str, str]:
status, payload = await mock_fetch_url(url)
if status == "Err":
return ("Err", payload)
return ("Ok", payload)
async def run_async_suite() -> list[dict]:
cases = []
# Case 1: Lazy Future polling (Pending -> Pending -> Ready) & async_task() -> 42
fut = PollCounterFuture(ticks=2, value=42)
polls = [fut.poll(), fut.poll(), fut.poll()]
log: list[str] = ["Start executing async task..."]
val = await execute_async_task(log)
log.append("Async task completed!")
actual_1 = {
"poll_trace": [list(p) for p in polls],
"task_value": val,
"execution_log": log,
}
expected_1 = {
"poll_trace": [["Pending", None], ["Pending", None], ["Ready", 42]],
"task_value": 42,
"execution_log": [
"Start executing async task...",
"Async task result: 42",
"Async task completed!",
],
}
cases.append(dict(
name="future_polling_and_async_task",
summary="Verify lazy Future Poll::Pending -> Poll::Ready state transitions and async_task() == 42",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: async fn, async block equivalent, and .await? error propagation
r1 = await hello()
r2 = await add(1, 2)
ok_fetch = await async_error_propagation("https://offline.local/posts/1")
err_fetch = await async_error_propagation("https://offline.local/missing")
actual_2 = {
"async_block_result": f"Result: {r1}, {r2}",
"fetch_ok": list(ok_fetch),
"fetch_err_propagated": err_fetch[0] == "Err",
}
expected_2 = {
"async_block_result": "Result: Hello, world!, 3",
"fetch_ok": ["Ok", '{"id": 1, "title": "offline-post"}'],
"fetch_err_propagated": True,
}
cases.append(dict(
name="async_block_and_await_question_mark",
summary="Verify async fn composition (hello + add) and .await? Ok/Err propagation using offline stub",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Spawned async tasks, bounded async mpsc channel, and async-style local file read
ch: asyncio.Queue[str] = asyncio.Queue(maxsize=32)
async def producer() -> None:
await ch.put("Hello, world!")
child = asyncio.create_task(producer())
received = await ch.get()
await child
with tempfile.TemporaryDirectory() as tmp:
fp = Path(tmp) / "file.txt"
fp.write_text("async-io-content", encoding="utf-8")
contents = await asyncio.to_thread(fp.read_text, encoding="utf-8")
actual_3 = {
"mpsc_received": f"Received: {received}",
"async_file_contents": contents,
"channel_capacity": ch.maxsize,
}
expected_3 = {
"mpsc_received": "Received: Hello, world!",
"async_file_contents": "async-io-content",
"channel_capacity": 32,
}
cases.append(dict(
name="async_spawn_mpsc_and_file_io",
summary="Verify spawned async task sending over capacity-32 mpsc channel and non-blocking temp file read",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
return cases
def main() -> None:
payload = {
"version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
"cases": asyncio.run(run_async_suite()),
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/rust-async-await-lab/explore-async-await.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-async-await.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1192.zip