fix(knowledge-base): 优化知识库页面,重构后端job队列
This commit is contained in:
1 parent
7e4a2037d8
commit
b476b58a91
38 files changed
+992
-428
No files matched your search
+14
-69
@@ -1,90 +1,35 @@
|
||||
"""
|
||||
backend/worker_kb.py
|
||||
文件用途:知识库最小 worker 入口
|
||||
|
||||
用途:知识库 worker 部署兼容入口(Compose / Supervisor 沿用此路径)。
|
||||
逻辑:Wave 2 转调 worker.py,默认 --queues kb;保留多进程并发配置。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from app import create_app
|
||||
from app.services.knowledge_cleaning.queue_service import process_next_clean_job
|
||||
|
||||
_LOG_FORMAT = '%(asctime)s %(levelname)s [kb-worker] %(message)s'
|
||||
_LOG_DATEFMT = '%Y-%m-%d %H:%M:%S'
|
||||
from worker import _configure_logging, _resolve_config_name, main
|
||||
|
||||
|
||||
def _configure_logging(worker_label: str = 'main') -> logging.Logger:
|
||||
logger = logging.getLogger(f'kb-worker.{worker_label}')
|
||||
if logger.handlers:
|
||||
return logger
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(logging.Formatter(f'{_LOG_FORMAT} [worker={worker_label}]', datefmt=_LOG_DATEFMT))
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
return logger
|
||||
def _worker_loop(worker_index: int) -> None:
|
||||
log = _configure_logging(str(worker_index))
|
||||
log.info('kb-worker process started index=%s', worker_index)
|
||||
main(queues=['kb'], config_name=_resolve_config_name())
|
||||
|
||||
|
||||
def _resolve_config_name() -> str:
|
||||
"""Keep the worker aligned with container/runtime environment selection.
|
||||
|
||||
Note: ``FLASK_ENV=test`` / ``ENV_NAME=test`` mean the *test deployment* host
|
||||
(``.env.test``), not pytest. Use ``production`` so DATABASE_URL from env_file
|
||||
is honored. ``testing`` is only for in-memory unit tests (``TestingConfig``).
|
||||
"""
|
||||
explicit = (os.getenv('APP_CONFIG') or '').strip().lower()
|
||||
if explicit:
|
||||
if explicit in ('testing', 'test'):
|
||||
# Allow explicit pytest-style config only when APP_CONFIG is set;
|
||||
# never infer this from FLASK_ENV=test on deploy hosts.
|
||||
return 'test'
|
||||
return explicit
|
||||
|
||||
env_name = (os.getenv('ENV_NAME') or os.getenv('FLASK_ENV') or 'production').strip().lower()
|
||||
mapping = {
|
||||
'dev': 'development',
|
||||
'development': 'development',
|
||||
# Deploy env files: test/prod hosts use real DB via ProductionConfig
|
||||
'test': 'production',
|
||||
'env': 'production',
|
||||
'prod': 'production',
|
||||
'production': 'production',
|
||||
# Pytest-only aliases (not used on deploy unless APP_CONFIG forces it)
|
||||
'testing': 'test',
|
||||
}
|
||||
return mapping.get(env_name, 'production')
|
||||
|
||||
|
||||
def _worker_loop(worker_index: int):
|
||||
worker_label = str(worker_index)
|
||||
log = _configure_logging(worker_label)
|
||||
app = create_app(_resolve_config_name())
|
||||
poll_seconds = float(app.config.get('KB_WORKER_POLL_SECONDS', 2))
|
||||
|
||||
with app.app_context():
|
||||
log.info('started, poll_seconds=%s', poll_seconds)
|
||||
while True:
|
||||
processed, message = process_next_clean_job()
|
||||
if not processed:
|
||||
time.sleep(poll_seconds)
|
||||
continue
|
||||
log.info('processed job: %s', message)
|
||||
|
||||
|
||||
def main():
|
||||
def main_kb() -> None:
|
||||
"""启动 KB worker;KB_WORKER_CONCURRENCY>1 时 fork 多进程。"""
|
||||
bootstrap_app = create_app(_resolve_config_name())
|
||||
concurrency = max(int(bootstrap_app.config.get('KB_WORKER_CONCURRENCY', 1) or 1), 1)
|
||||
|
||||
if concurrency == 1:
|
||||
_worker_loop(1)
|
||||
main(queues=['kb'], config_name=_resolve_config_name())
|
||||
return
|
||||
|
||||
log = _configure_logging('master')
|
||||
log.info('starting %s worker processes', concurrency)
|
||||
log.info('starting %s kb worker processes', concurrency)
|
||||
workers: list[mp.Process] = []
|
||||
for index in range(concurrency):
|
||||
proc = mp.Process(target=_worker_loop, args=(index + 1,), name=f'kb-worker-{index + 1}')
|
||||
@@ -95,7 +40,7 @@ def main():
|
||||
for proc in workers:
|
||||
proc.join()
|
||||
except KeyboardInterrupt:
|
||||
log.info('stopping worker pool')
|
||||
log.info('stopping kb worker pool')
|
||||
for proc in workers:
|
||||
if proc.is_alive():
|
||||
proc.terminate()
|
||||
@@ -105,4 +50,4 @@ def main():
|
||||
|
||||
if __name__ == '__main__':
|
||||
mp.freeze_support()
|
||||
main()
|
||||
main_kb()
|
||||
Reference in new issue
Block a user