factory.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """数据处理工具的装配工厂 —— **唯一需要改动的替换入口**。
  2. 默认加载 ``pipeline.DefaultCustomsProcessor``。
  3. 如果要把整个数据处理工具换成另一套实现(例如改成 PySpark 版本、换成
  4. 流式处理、或换一个完全不同口径的统计引擎),只要满足 ``contract.CustomsProcessor``
  5. 协议,然后用环境变量指向它:
  6. .. code-block:: bash
  7. set CUSTOMS_PROCESSOR=my_company.customs:MyProcessor
  8. 平台其余模块(BFF、Agent 工具、前端 /api/process)都不需要改动。
  9. """
  10. from __future__ import annotations
  11. import importlib
  12. import os
  13. from .contract import CustomsProcessor
  14. from .pipeline import DefaultCustomsProcessor
  15. DEFAULT_SPEC = "toolsvc.customs.pipeline:DefaultCustomsProcessor"
  16. def _load(spec: str) -> CustomsProcessor:
  17. module_name, _, attribute = spec.partition(":")
  18. if not module_name or not attribute:
  19. raise ValueError(f"CUSTOMS_PROCESSOR 格式应为 '模块:类名',当前为 {spec!r}")
  20. module = importlib.import_module(module_name)
  21. target = getattr(module, attribute)
  22. instance = target() if isinstance(target, type) else target
  23. for method in ("process",):
  24. if not hasattr(instance, method):
  25. raise TypeError(f"{spec} 未实现 CustomsProcessor.{method}")
  26. return instance
  27. _cached: CustomsProcessor | None = None
  28. def load_processor() -> CustomsProcessor:
  29. """返回单例处理器(线程内复用规则库缓存)。"""
  30. global _cached
  31. if _cached is None:
  32. _cached = _load(os.environ.get("CUSTOMS_PROCESSOR", DEFAULT_SPEC))
  33. return _cached
  34. def reset_processor() -> None:
  35. """测试用:清掉缓存。"""
  36. global _cached
  37. _cached = None