environment.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. """网页、独立脚本和集成测试共用的进程级运行环境。"""
  2. from __future__ import annotations
  3. import asyncio
  4. from contextlib import AsyncExitStack
  5. import os
  6. import threading
  7. import config
  8. from agents import agent_memory, agent_registry
  9. from billing import pricing
  10. from db import db_conn, run_store
  11. from extensions.registry import approval_names, load_extensions
  12. from obs import get_logger, setup_logging
  13. logger = get_logger(__name__)
  14. # 底层缓存与连接仍是进程级单例;拒绝嵌套/并行环境,防止一方关闭另一方的资源。
  15. _owner_lock = threading.Lock()
  16. async def _retry_billing(stop: asyncio.Event) -> None:
  17. from billing.meter import retry_pending
  18. while not stop.is_set():
  19. try:
  20. await asyncio.to_thread(retry_pending)
  21. except Exception:
  22. logger.exception("重试待结算流水失败")
  23. try:
  24. await asyncio.wait_for(stop.wait(), 60)
  25. except asyncio.TimeoutError:
  26. pass
  27. async def _stop_billing(stop: asyncio.Event, task: asyncio.Task) -> None:
  28. stop.set()
  29. # 不取消 to_thread:必须等数据库写入完成才能关闭连接。
  30. await task
  31. async def _prewarm() -> None:
  32. ok = await agent_registry.prewarm()
  33. logger.info("agent 预热%s", "完成" if ok else "失败(将在首次请求时重试)")
  34. async def _join(task: asyncio.Task) -> None:
  35. # 初始化和编译可能在线程中进行,取消协程并不能停止底层工作。
  36. await task
  37. def _check_single_process() -> None:
  38. workers = os.getenv("WEB_CONCURRENCY", "")
  39. try:
  40. count = int(workers) if workers else 1
  41. except ValueError:
  42. count = 1
  43. if count > 1:
  44. logger.warning(
  45. "检测到 WEB_CONCURRENCY=%s:checkpoint / 并发闸 / 调度器 "
  46. "使用进程级状态,生产请用 --workers 1。", workers,
  47. )
  48. class RuntimeEnvironment:
  49. """使用 ``async with`` 管理一次完整生命周期。
  50. 默认加载扩展、建表、初始化定价/checkpoint、恢复中断记录、后台预热和重试计费。
  51. 独立脚本默认不启动调度器;网页入口显式传 ``scheduler=True``。
  52. 同一进程只允许一个活动环境,可在退出后重新进入;退出前调用方必须等待
  53. 自己创建的执行任务结束(或取消并等待收尾),再释放共享资源。
  54. """
  55. def __init__(self, *, scheduler: bool = False, prewarm: bool = True,
  56. billing_retry: bool = True, recover_interrupted: bool = True) -> None:
  57. self.scheduler = scheduler
  58. self.prewarm = prewarm
  59. self.billing_retry = billing_retry
  60. self.recover_interrupted = recover_interrupted
  61. self._stack: AsyncExitStack | None = None
  62. async def __aenter__(self) -> RuntimeEnvironment:
  63. if not _owner_lock.acquire(blocking=False):
  64. raise RuntimeError("已有活动的 RuntimeEnvironment,请复用外层环境")
  65. stack = self._stack = AsyncExitStack()
  66. stack.callback(_owner_lock.release)
  67. try:
  68. setup_logging(config.LOG_LEVEL, config.LOG_FORMAT)
  69. config.log_config_sources()
  70. _check_single_process()
  71. load_extensions()
  72. approval_names()
  73. stack.callback(db_conn.close)
  74. db_conn.init_schema()
  75. logger.info("存储就绪 %s", db_conn.health())
  76. pricing.seed_default_pricing()
  77. if self.recover_interrupted:
  78. run_store.recover_interrupted()
  79. # 注册在初始化前,部分初始化失败也会清理。
  80. stack.push_async_callback(agent_memory.close_checkpointer)
  81. agent_registry.invalidate()
  82. stack.callback(agent_registry.invalidate)
  83. init_task = asyncio.create_task(agent_memory.init_checkpointer(), name="runtime-checkpoint-init")
  84. stack.push_async_callback(_join, init_task)
  85. # aiosqlite 在线程中连接;取消调用方时先等初始化结束,再关闭连接。
  86. await asyncio.shield(init_task)
  87. if self.prewarm:
  88. task = asyncio.create_task(_prewarm(), name="runtime-prewarm")
  89. stack.push_async_callback(_join, task)
  90. if self.billing_retry:
  91. stop = asyncio.Event()
  92. task = asyncio.create_task(_retry_billing(stop), name="runtime-billing")
  93. stack.push_async_callback(_stop_billing, stop, task)
  94. if self.scheduler:
  95. from scheduler import scheduler
  96. stack.push_async_callback(scheduler.shutdown)
  97. task = asyncio.create_task(scheduler.start(), name="runtime-scheduler-init")
  98. stack.push_async_callback(_join, task)
  99. await asyncio.shield(task)
  100. if not config.OPENAI_API_KEY:
  101. logger.warning("OPENAI_API_KEY 未配置,对话会失败——请在 .env 里设置")
  102. logger.info("运行环境就绪 scheduler=%s", self.scheduler)
  103. return self
  104. except BaseException:
  105. await self._close()
  106. raise
  107. async def _close(self) -> None:
  108. stack = self._stack
  109. if stack is None:
  110. return
  111. # shield 保证取消(含二次取消)时仍完成整条资源清理链。
  112. task = asyncio.create_task(stack.aclose(), name="runtime-close")
  113. cancelled = False
  114. try:
  115. while not task.done():
  116. try:
  117. await asyncio.shield(task)
  118. except asyncio.CancelledError:
  119. cancelled = True
  120. task.result()
  121. finally:
  122. self._stack = None
  123. logger.info("运行环境已关闭")
  124. if cancelled:
  125. raise asyncio.CancelledError
  126. async def __aexit__(self, exc_type, exc, tb) -> None:
  127. await self._close()