environment.py 6.2 KB

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