66 lines
1.8 KiB
Python
66 lines
1.8 KiB
Python
"""
|
|
backend/worker_kb.py
|
|
文件用途:知识库最小 worker 入口
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
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'
|
|
|
|
|
|
def _configure_logging() -> logging.Logger:
|
|
logger = logging.getLogger('kb-worker')
|
|
if logger.handlers:
|
|
return logger
|
|
handler = logging.StreamHandler(sys.stdout)
|
|
handler.setFormatter(logging.Formatter(_LOG_FORMAT, datefmt=_LOG_DATEFMT))
|
|
logger.addHandler(handler)
|
|
logger.setLevel(logging.INFO)
|
|
logger.propagate = False
|
|
return logger
|
|
|
|
|
|
def _resolve_config_name() -> str:
|
|
"""Keep the worker aligned with container/runtime environment selection."""
|
|
explicit = os.getenv('APP_CONFIG')
|
|
if explicit:
|
|
return explicit.strip().lower()
|
|
|
|
flask_env = os.getenv('FLASK_ENV', 'production').strip().lower()
|
|
mapping = {
|
|
'dev': 'development',
|
|
'development': 'development',
|
|
'test': 'testing',
|
|
'testing': 'testing',
|
|
'prod': 'production',
|
|
'production': 'production',
|
|
}
|
|
return mapping.get(flask_env, 'production')
|
|
|
|
|
|
def main():
|
|
log = _configure_logging()
|
|
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)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|