帮助开发者构建含生命周期管理、WebSocket与SSE的 HTTP 服务模式
复制安装指令,让 AI 自动完成配置 · 推荐新手
请帮我安装 askskill 上的 "http-service-patterns" 技能: 1. 下载 https://raw.githubusercontent.com/microsoft/amplifier-bundle-skills/main/skills/http-service-patterns/SKILL.md 2. 保存为 ~/.claude/skills/http-service-patterns/SKILL.md 3. 装好后重载技能,告诉我可以用了
请给我一个 FastAPI HTTP 服务模板,包含应用生命周期管理、启动时初始化资源、关闭时释放资源,并提供一个健康检查接口。
输出一个包含启动与关闭钩子、基础路由和项目结构建议的 FastAPI 服务示例。
请设计一个 FastAPI 服务,在后台持续轮询外部接口获取状态,每隔 30 秒更新一次缓存,并提供 API 返回最新结果。
输出包含后台循环、异常重试、缓存更新和查询接口的实现方案或代码。
请给我一个 HTTP 服务示例,同时支持 WebSocket 双向消息中继和 SSE 单向事件流推送,并说明各自适用场景。
输出包含 WebSocket、中继逻辑、SSE 推送接口及场景说明的完整示例。
Problem: You need a web service that does more than serve requests — it has a background loop reconciling state, it proxies WebSocket connections to a backend process, and it must start reliably even when the previous instance didn't exit cleanly.
Approach: FastAPI lifespan for startup/shutdown, asyncio.create_task for background loops, bidirectional WebSocket relay for proxying, and pre-bind port cleanup to prevent systemd crash-loops.
Pattern proven in production across multiple Python CLI tools and web services.
When systemd restarts a service, the old process may still hold the port in TIME_WAIT. The new process fails to bind, exits with status=1, systemd restarts it, repeat. In one production deployment, 2,075+ systemd restarts occurred before manual intervention.
The fix runs before uvicorn.run():
def _kill_stale_port_holder(port: int) -> None:
"""Kill any existing process on *port* to prevent EADDRINUSE crash-loops."""
try:
result = subprocess.run(
["lsof", "-ti", f":{port}"],
capture_output=True, text=True, timeout=5,
)
if result.returncode == 0 and result.stdout.strip():
my_pid = os.getpid()
for pid_str in result.stdout.strip().split("\n"):
pid = int(pid_str.strip())
if pid != my_pid:
os.kill(pid, signal.SIGTERM)
time.sleep(1) # Brief wait for the port to be released
except Exception:
pass # lsof not available — proceed; uvicorn will fail naturally
Called right before server start:
_kill_stale_port_holder(port)
Use the FastAPI lifespan pattern to start background tasks at startup and clean them up at shutdown.
Starting a poll loop and an httpx client:
async def lifespan(app: FastAPI):
global _poll_task, _http_client
await kill_orphan_processes()
_poll_task = asyncio.create_task(_poll_loop())
_http_client = httpx.AsyncClient(verify=False)
app.state.http_client = _http_client
yield
# Shutdown
_poll_task.cancel()
await _http_client.aclose()
Starting both a monitor loop and a watchdog loop:
# Example: dual-loop lifespan for services that need both monitoring and maintenance
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
client = await _try_create_client() # graceful degradation if unavailable
app.state.orchestrator = Orchestrator(client=client)
monitor_instance = asyncio.create_task(monitor_loop(app))
watchdog_instance = asyncio.create_task(
app.state.orchestrator.watchdog_loop(app.state.instance_store))
try:
yield
finally:
watchdog_instance.cancel()
monitor_instance.cancel()
if client is not None:
await client.shutdown()
When proxying browser WebSocket connections to a backend process, check auth and verify the backend is alive BEFORE accepting the browser WS:
@app.websocket("/terminal/ws")
async def terminal_ws_proxy(websocket: WebSocket) -> None:
# Auth check BEFORE accept — middleware doesn't cover WebSocket scope
if not await _ws_auth_check(websocket):
return
# Ensure backend is reachable BEFORE accepting the browser WS
if not _is_backend_alive():
# Auto-spawn backend, wait for it to bind
...
await websocket.accept(subprotocol="tty")
async with websockets.connect(
f"ws://localhost:{BACKEND_PORT}/ws",
subprotocols=[Subprotocol("tty")]
) as backend_ws:
# Two concurrent tasks: client→backend and backend→client
async def client_to_backend():
while True:
…
帮助你调研、规划并并行执行大规模代码变更,让多个代理分别提交 PR。
帮助你安全编排 Docker 容器任务,并搭建可复现的开发运行环境
用多模型视觉能力分析图片内容、提取文字并回答图像相关问题。
帮助开发者设计安全持久的配置与状态文件管理模式,兼顾默认值合并和崩溃恢复。
以资深工程师视角审视架构、遗留重构与工具选型,给出务实建议。
帮助开发与运维设计兼顾本地顺畅和远程安全的认证与 TLS 接入方案。
提供 FastAPI 项目结构、鉴权、事务分层与测试的最佳实践指导
提供基于文件系统的进程间通信模式,适合无消息队列的本地协作场景
帮助你设计或评估Web服务架构、API模式、扩展性与可靠性问题。
帮助设计或评估单页应用架构,涵盖路由、状态、性能与离线能力。
帮助开发者快速理解并搭建支持流式 HTTP 的简单 MCP 服务端示例
帮助开发者处理 Vite 配置、插件、构建优化与 SSR 等实战问题