perf(kb):知识库数据清洗同步改异步优化;chat中查假期请假agent入口优化
This commit is contained in:
1 parent
61ebb46c0f
commit
c3b63df2f5
11 files changed
+839
-171
No files matched your search
+20
-16
@@ -25,6 +25,13 @@ from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
||||
|
||||
|
||||
def _can_use_leave_feature(agent_proxy) -> bool:
|
||||
agent_name = str(getattr(agent_proxy, 'name', None) or '').strip()
|
||||
return agent_name in LEAVE_FEATURE_AGENT_NAMES
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
def _session_title_from_text(text: str) -> str:
|
||||
@@ -1056,27 +1063,24 @@ def chat_completions():
|
||||
|
||||
if normalized_files and PLMOracleService.supports(query, agent_proxy):
|
||||
raise ValidationError('This route does not support attachments')
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
leave_supported = HRLeaveSQLServerService.supports(query)
|
||||
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
|
||||
if PLMOracleService.supports(query, agent_proxy):
|
||||
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
elif leave_supported and leave_feature_enabled:
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
elif leave_supported:
|
||||
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
|
||||
elif kb_type == 'ERP知识库':
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.text2sql import Text2SQLService
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
|
||||
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
|
||||
|
||||
def relay_stream():
|
||||
created_event = {
|
||||
|
||||
@@ -19,7 +19,6 @@ from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup,
|
||||
from app.services.knowledge_cleaning.dify_sync_service import delete_document_from_dify
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job, enqueue_kb_job
|
||||
from app.services.knowledge_cleaning.settings_service import get_kb_dify_health_payload, get_kb_dify_settings, save_kb_dify_settings
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_sync_job
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
knowledge_base_bp = Blueprint('knowledge_base', __name__)
|
||||
|
||||
@@ -74,6 +73,18 @@ def _current_version(document: KbDocument | None) -> KbDocumentVersion | None:
|
||||
return None
|
||||
return next((item for item in versions if item.is_current), versions[0])
|
||||
|
||||
|
||||
def _latest_job_for_version(version_id: int, job_type: str) -> KbJob | None:
|
||||
return (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.document_version_id == version_id,
|
||||
KbJob.job_type == job_type,
|
||||
)
|
||||
.order_by(KbJob.created_at.desc(), KbJob.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
def _resolve_storage_path(path_value: str | None) -> Path | None:
|
||||
if not path_value:
|
||||
return None
|
||||
@@ -166,6 +177,26 @@ def _save_upload(file_storage, target_path: Path):
|
||||
def _get_active_path_upload_job(group_id: int) -> KbJob | None:
|
||||
return db.session.query(KbJob).filter(KbJob.group_id == group_id, KbJob.job_type == 'path_upload', KbJob.status.in_(('draft', 'staging', 'queued', 'running'))).order_by(KbJob.created_at.desc(), KbJob.id.desc()).first()
|
||||
|
||||
|
||||
def _upsert_path_upload_job_files(job: KbJob, requested_files: list[dict]) -> None:
|
||||
payload = dict(job.payload_json or {})
|
||||
files = list(payload.get('files') or [])
|
||||
|
||||
for requested_item in requested_files:
|
||||
relative_path = str(requested_item.get('relative_path') or '').strip()
|
||||
if not relative_path:
|
||||
continue
|
||||
existing_item = _find_path_upload_file_item(files, relative_path)
|
||||
if existing_item is None:
|
||||
files.append(requested_item)
|
||||
continue
|
||||
if not str(existing_item.get('original_name') or '').strip():
|
||||
existing_item['original_name'] = requested_item.get('original_name')
|
||||
|
||||
_sync_path_upload_job_payload(job, files)
|
||||
if job.status in ('draft', 'staging', 'queued', 'running'):
|
||||
_refresh_path_upload_job_state(job)
|
||||
|
||||
def _sanitize_relative_path(relative_path: str | None, fallback_name: str) -> str:
|
||||
raw = str(relative_path or '').replace('\\', '/').strip().lstrip('/')
|
||||
normalized = normpath(raw) if raw else fallback_name
|
||||
@@ -231,6 +262,51 @@ def _sync_path_upload_job_payload(job: KbJob, files: list[dict]):
|
||||
job.result_json = result
|
||||
return (payload, result)
|
||||
|
||||
|
||||
def _refresh_path_upload_job_state(job: KbJob) -> None:
|
||||
payload = dict(job.payload_json or {})
|
||||
result = dict(job.result_json or {})
|
||||
total = max(int(result.get('total') or payload.get('total_files') or 0), 0)
|
||||
success = int(result.get('success') or 0)
|
||||
failed = int(result.get('failed') or 0)
|
||||
processed = int(result.get('processed') or (success + failed) or 0)
|
||||
files = list(payload.get('files') or [])
|
||||
has_pending = any(
|
||||
str(item.get('status') or '').lower() in ('queued', 'uploading')
|
||||
for item in files
|
||||
)
|
||||
|
||||
payload['current_file'] = ''
|
||||
job.payload_json = payload
|
||||
job.progress = min(int(processed * 100 / total), 100) if total else 100
|
||||
|
||||
if total == 0:
|
||||
job.status = 'cancelled'
|
||||
job.finished_at = datetime.utcnow()
|
||||
job.progress = 100
|
||||
job.message = '路径上传记录为空'
|
||||
job.error_message = None
|
||||
return
|
||||
|
||||
if has_pending or processed < total:
|
||||
job.status = 'staging'
|
||||
job.finished_at = None
|
||||
job.message = f'已上传并提交清洗 {processed}/{total} 个文件'
|
||||
job.error_message = None
|
||||
return
|
||||
|
||||
job.finished_at = datetime.utcnow()
|
||||
job.progress = 100
|
||||
if failed > 0:
|
||||
job.status = 'failed'
|
||||
job.message = f'路径上传完成,成功 {success} 条,失败 {failed} 条'
|
||||
job.error_message = f'部分文件上传失败:{failed} 条'
|
||||
return
|
||||
|
||||
job.status = 'success'
|
||||
job.message = f'路径上传完成,成功 {success} 条'
|
||||
job.error_message = None
|
||||
|
||||
def _remove_path_upload_staged_file(staged_path: str | None):
|
||||
candidate = _resolve_storage_path(staged_path)
|
||||
if not candidate or not candidate.exists():
|
||||
@@ -377,7 +453,24 @@ def create_path_upload_job(group_id: int):
|
||||
raise NotFoundError('Knowledge base group not found')
|
||||
existing_job = _get_active_path_upload_job(group_id)
|
||||
if existing_job:
|
||||
raise ConflictError('有文件正在上传请稍等再试~', details={'job': _serialize_job(existing_job)})
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_files = data.get('files') or []
|
||||
files = []
|
||||
if isinstance(raw_files, list):
|
||||
for item in raw_files:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
files.append(_build_path_upload_file_item(item.get('relative_path'), item.get('original_name')))
|
||||
except ValueError:
|
||||
continue
|
||||
if files:
|
||||
_upsert_path_upload_job_files(existing_job, files)
|
||||
db.session.commit()
|
||||
payload = _serialize_job(existing_job)
|
||||
payload['reused_existing'] = True
|
||||
payload['message'] = payload.get('message') or '检测到未完成的路径上传任务,已自动续传'
|
||||
return jsonify(payload)
|
||||
data = request.get_json(silent=True) or {}
|
||||
total_files = max(int(data.get('total_files') or 0), 0)
|
||||
selected_paths = data.get('selected_paths') or []
|
||||
@@ -427,6 +520,11 @@ def upload_path_job_file(job_id: int):
|
||||
payload = dict(job.payload_json or {})
|
||||
files = list(payload.get('files') or [])
|
||||
entry = _find_path_upload_file_item(files, relative_path)
|
||||
if entry is not None and str(entry.get('status') or '').lower() == 'success' and entry.get('document_id') and entry.get('version_id'):
|
||||
_sync_path_upload_job_payload(job, files)
|
||||
_refresh_path_upload_job_state(job)
|
||||
db.session.commit()
|
||||
return jsonify(_serialize_job(job))
|
||||
if entry is None:
|
||||
entry = _build_path_upload_file_item(relative_path, fallback_name)
|
||||
files.append(entry)
|
||||
@@ -434,11 +532,37 @@ def upload_path_job_file(job_id: int):
|
||||
entry['staged_path'] = str(target_path)
|
||||
entry['size'] = file_size
|
||||
entry['sha256'] = sha256
|
||||
entry['status'] = 'queued'
|
||||
entry['status'] = 'uploading'
|
||||
entry['error'] = None
|
||||
payload, result = _sync_path_upload_job_payload(job, files)
|
||||
job.message = f"已暂存 {job.payload_json.get('staged_count')}/{job.payload_json.get('total_files') or len(files)} 个文件"
|
||||
job.result_json = result
|
||||
entry['document_id'] = None
|
||||
entry['version_id'] = None
|
||||
payload['current_file'] = relative_path
|
||||
job.status = 'staging'
|
||||
job.started_at = job.started_at or datetime.utcnow()
|
||||
payload, _result = _sync_path_upload_job_payload(job, files)
|
||||
job.payload_json = payload
|
||||
job.message = f'正在上传并提交清洗:{relative_path}'
|
||||
|
||||
try:
|
||||
from app.services.knowledge_cleaning.tasks import _register_document_version_from_staged_file
|
||||
|
||||
document, version, _clean_job = _register_document_version_from_staged_file(
|
||||
group_id=job.group_id,
|
||||
relative_path=relative_path,
|
||||
staged_path=target_path,
|
||||
original_name=fallback_name,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
entry['status'] = 'success'
|
||||
entry['document_id'] = document.id
|
||||
entry['version_id'] = version.id
|
||||
entry['error'] = None
|
||||
except Exception as exc:
|
||||
entry['status'] = 'failed'
|
||||
entry['error'] = str(exc)
|
||||
|
||||
_sync_path_upload_job_payload(job, files)
|
||||
_refresh_path_upload_job_state(job)
|
||||
db.session.commit()
|
||||
return (jsonify(_serialize_job(job)), 201)
|
||||
|
||||
@@ -468,12 +592,7 @@ def mark_path_job_file_failed(job_id: int):
|
||||
entry['error'] = error_message
|
||||
entry['original_name'] = entry.get('original_name') or original_name or Path(relative_path).name
|
||||
_sync_path_upload_job_payload(job, files)
|
||||
if str(job.status or '').lower() in ('draft', 'staging') and not any(str(item.get('staged_path') or '').strip() for item in files):
|
||||
job.status = 'failed'
|
||||
job.progress = 100
|
||||
job.finished_at = datetime.utcnow()
|
||||
job.message = f'路径上传完成,成功 0 条,失败 {job.result_json.get("failed", 0)} 条'
|
||||
job.error_message = error_message
|
||||
_refresh_path_upload_job_state(job)
|
||||
db.session.commit()
|
||||
return jsonify(_serialize_job(job))
|
||||
|
||||
@@ -483,6 +602,8 @@ def finalize_path_upload_job(job_id: int):
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job or job.job_type != 'path_upload':
|
||||
raise NotFoundError('路径上传任务不存在')
|
||||
if job.status in ('success', 'failed', 'cancelled'):
|
||||
return jsonify(_serialize_job(job))
|
||||
if job.status not in ('draft', 'staging'):
|
||||
raise ConflictError('当前任务不允许提交执行')
|
||||
payload = dict(job.payload_json or {})
|
||||
@@ -492,24 +613,24 @@ def finalize_path_upload_job(job_id: int):
|
||||
staged_files = [item for item in files if str(item.get('staged_path') or '').strip()]
|
||||
if not staged_files:
|
||||
_sync_path_upload_job_payload(job, files)
|
||||
job.status = 'failed'
|
||||
job.progress = 100
|
||||
job.finished_at = datetime.utcnow()
|
||||
failed_count = int(job.result_json.get('failed') or 0)
|
||||
job.message = f'路径上传完成,成功 0 条,失败 {failed_count} 条'
|
||||
job.error_message = '当前批次没有成功暂存的文件'
|
||||
_refresh_path_upload_job_state(job)
|
||||
if job.status != 'failed':
|
||||
job.status = 'failed'
|
||||
job.message = '当前批次没有成功暂存的文件'
|
||||
job.error_message = '当前批次没有成功暂存的文件'
|
||||
db.session.commit()
|
||||
return jsonify(_serialize_job(job))
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.message = '等待后台批量导入文档'
|
||||
payload['finalized_at'] = datetime.utcnow().isoformat()
|
||||
job.payload_json = payload
|
||||
job.created_by_id = getattr(current_user, 'id', None)
|
||||
_sync_path_upload_job_payload(job, files)
|
||||
_refresh_path_upload_job_state(job)
|
||||
db.session.commit()
|
||||
enqueue_kb_job(job.id)
|
||||
refreshed = db.session.get(KbJob, job.id)
|
||||
return jsonify(_serialize_job(refreshed))
|
||||
response_payload = _serialize_job(refreshed)
|
||||
response_payload['queue_result'] = 'inline_per_file'
|
||||
response_payload['accepted'] = True
|
||||
return (jsonify(response_payload), 202)
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['DELETE'])
|
||||
def delete_path_job_file(job_id: int):
|
||||
@@ -692,10 +813,75 @@ def upload_document_version(document_id: int):
|
||||
db.session.add(upload_job)
|
||||
db.session.add(clean_job)
|
||||
db.session.commit()
|
||||
enqueue_clean_job(clean_job.id)
|
||||
_enqueued, queue_result = enqueue_clean_job(clean_job.id)
|
||||
db.session.expire_all()
|
||||
version = db.session.get(KbDocumentVersion, version.id)
|
||||
return (jsonify(_serialize_version(version)), 201)
|
||||
clean_job = db.session.get(KbJob, clean_job.id)
|
||||
return (jsonify({
|
||||
'accepted': True,
|
||||
'message': '文件上传成功,清洗已排队',
|
||||
'queue_result': queue_result,
|
||||
'version': _serialize_version(version),
|
||||
'clean_job': _serialize_job(clean_job) if clean_job else None,
|
||||
}), 201)
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/clean', methods=['POST'])
|
||||
@require_admin
|
||||
def submit_document_clean(document_id: int):
|
||||
current_user = get_current_user()
|
||||
document = (
|
||||
db.session.query(KbDocument)
|
||||
.options(joinedload(KbDocument.versions))
|
||||
.filter(KbDocument.id == document_id, KbDocument.is_deleted.is_(False))
|
||||
.first()
|
||||
)
|
||||
if not document:
|
||||
raise NotFoundError('Knowledge base document not found')
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
raise ValidationError('当前文档暂无可清洗版本')
|
||||
|
||||
latest_clean_job = _latest_job_for_version(version.id, 'clean')
|
||||
if latest_clean_job and latest_clean_job.status in ('queued', 'running'):
|
||||
payload = _serialize_job(latest_clean_job)
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'already_queued'
|
||||
payload['message'] = latest_clean_job.message or '清洗任务已在处理中'
|
||||
return jsonify(payload), 202
|
||||
|
||||
version.status = 'uploaded'
|
||||
version.error_message = None
|
||||
if document.status == 'failed':
|
||||
document.status = 'uploaded'
|
||||
document.updated_by_id = getattr(current_user, 'id', None)
|
||||
|
||||
clean_job = KbJob(
|
||||
job_type='clean',
|
||||
status='queued',
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=0,
|
||||
message='等待清洗任务执行',
|
||||
payload_json={
|
||||
'document_version_id': version.id,
|
||||
'document_id': document.id,
|
||||
'source_file_name': version.source_file_name,
|
||||
'retry_mode': 'manual',
|
||||
},
|
||||
created_by_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.add(clean_job)
|
||||
db.session.commit()
|
||||
|
||||
_enqueued, queue_result = enqueue_clean_job(clean_job.id)
|
||||
refreshed = db.session.get(KbJob, clean_job.id)
|
||||
payload = _serialize_job(refreshed) if refreshed else {'id': clean_job.id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = queue_result
|
||||
payload['message'] = refreshed.message if refreshed else '清洗任务已提交,等待后台处理'
|
||||
return jsonify(payload), 202
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync', methods=['POST'])
|
||||
@require_admin
|
||||
@@ -710,13 +896,13 @@ def sync_document(document_id: int):
|
||||
sync_job = KbJob(job_type='sync_dify', status='queued', group_id=document.group_id, document_id=document.id, document_version_id=version.id, progress=0, message='等待同步到 Dify', payload_json={'document_version_id': version.id, 'document_id': document.id}, created_by_id=getattr(current_user, 'id', None))
|
||||
db.session.add(sync_job)
|
||||
db.session.commit()
|
||||
success, message = run_sync_job(sync_job.id)
|
||||
_enqueued, queue_result = enqueue_kb_job(sync_job.id)
|
||||
refreshed = db.session.get(KbJob, sync_job.id)
|
||||
payload = _serialize_job(refreshed) if refreshed else {'id': sync_job.id}
|
||||
payload['run_result'] = message
|
||||
if not success:
|
||||
payload['error'] = (refreshed.error_message if refreshed else None) or message
|
||||
return (jsonify(payload), 200 if success else 400)
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = queue_result
|
||||
payload['message'] = refreshed.message if refreshed else '同步任务已提交,等待后台处理'
|
||||
return (jsonify(payload), 202)
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['PATCH'])
|
||||
def update_document(document_id: int):
|
||||
@@ -769,13 +955,51 @@ def run_job(job_id: int):
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
raise NotFoundError('任务不存在')
|
||||
if job.job_type == 'clean':
|
||||
success, message = run_clean_job(job_id)
|
||||
elif job.job_type == 'sync_dify':
|
||||
success, message = run_sync_job(job_id)
|
||||
else:
|
||||
|
||||
if job.job_type not in ('clean', 'sync_dify'):
|
||||
raise ValidationError('当前仅支持手动执行 clean 或 sync_dify 任务')
|
||||
|
||||
if job.status in ('queued', 'running'):
|
||||
refreshed = db.session.get(KbJob, job_id)
|
||||
payload = _serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'already_queued'
|
||||
payload['run_result'] = '任务已在后台处理中'
|
||||
return jsonify(payload), 202
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id) if job.document_version_id else None
|
||||
|
||||
if job.job_type == 'clean':
|
||||
if not version:
|
||||
raise NotFoundError('关联文档版本不存在')
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.started_at = None
|
||||
job.finished_at = None
|
||||
job.error_message = None
|
||||
job.message = '等待清洗任务执行'
|
||||
version.status = 'uploaded'
|
||||
version.error_message = None
|
||||
if version.document:
|
||||
version.document.status = 'uploaded'
|
||||
else:
|
||||
if not version:
|
||||
raise NotFoundError('关联文档版本不存在')
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.started_at = None
|
||||
job.finished_at = None
|
||||
job.error_message = None
|
||||
job.message = '等待同步到 Dify'
|
||||
if version.status in ('failed', 'ready', 'synced'):
|
||||
version.error_message = None
|
||||
|
||||
db.session.commit()
|
||||
|
||||
_enqueued, queue_result = enqueue_kb_job(job.id)
|
||||
refreshed = db.session.get(KbJob, job_id)
|
||||
payload = _serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||
payload['run_result'] = message
|
||||
return (jsonify(payload), 200 if success else 400)
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = queue_result
|
||||
payload['run_result'] = '任务已提交后台异步执行'
|
||||
return jsonify(payload), 202
|
||||
@@ -55,10 +55,13 @@ class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'sync').strip().lower()
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
|
||||
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
|
||||
# 数据库连接池配置
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 20,
|
||||
@@ -69,7 +72,7 @@ class Config:
|
||||
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
|
||||
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
|
||||
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
|
||||
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', 'sync').strip().lower()
|
||||
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
|
||||
@@ -34,6 +34,9 @@ _BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||
# Backward-compatible alias for tests and older callers that still patch/read
|
||||
# the historical backend/.env location directly.
|
||||
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
@@ -180,7 +183,7 @@ def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
merged: dict[str, str] = {}
|
||||
for env_path in (LEGACY_BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||
if not env_path.exists():
|
||||
continue
|
||||
try:
|
||||
|
||||
@@ -12,6 +12,7 @@ import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app import db
|
||||
from app.models import KbDocumentVersion, KbJob
|
||||
@@ -79,8 +80,8 @@ def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
|
||||
- manual: 保留 queued,等待管理台手动执行。
|
||||
"""
|
||||
mode = str(
|
||||
current_app.config.get('TASK_EXECUTION_MODE')
|
||||
or current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')
|
||||
current_app.config.get('KB_TASK_EXECUTION_MODE')
|
||||
or current_app.config.get('TASK_EXECUTION_MODE', 'worker')
|
||||
).strip().lower()
|
||||
|
||||
job = db.session.get(KbJob, job_id)
|
||||
@@ -88,12 +89,14 @@ def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
|
||||
return False, 'job_not_found'
|
||||
|
||||
if mode == 'sync':
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job, run_sync_job
|
||||
|
||||
if job.job_type == 'clean':
|
||||
return run_clean_job(job_id)
|
||||
if job.job_type == 'path_upload':
|
||||
return run_path_upload_job(job_id)
|
||||
if job.job_type == 'sync_dify':
|
||||
return run_sync_job(job_id)
|
||||
return False, f'unsupported_sync_job:{job.job_type}'
|
||||
|
||||
if mode in ('worker', 'rq'):
|
||||
@@ -106,23 +109,57 @@ def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
return enqueue_kb_job(job_id)
|
||||
|
||||
|
||||
def claim_next_kb_job() -> KbJob | None:
|
||||
"""
|
||||
原子领取下一条 queued 任务,避免并发 worker 重复消费同一条记录。
|
||||
|
||||
当前运行在 PostgreSQL,可安全使用 FOR UPDATE SKIP LOCKED。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
job = (
|
||||
db.session.query(KbJob)
|
||||
.filter(KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')), KbJob.status == 'queued')
|
||||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||||
.with_for_update(skip_locked=True)
|
||||
.first()
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
logger.exception('failed to claim next kb job')
|
||||
return None
|
||||
|
||||
if not job:
|
||||
db.session.rollback()
|
||||
return None
|
||||
|
||||
job.status = 'running'
|
||||
job.started_at = job.started_at or now
|
||||
job.progress = max(int(job.progress or 0), 1)
|
||||
if job.job_type == 'clean':
|
||||
job.message = 'worker 已领取清洗任务'
|
||||
elif job.job_type == 'sync_dify':
|
||||
job.message = 'worker 已领取同步任务'
|
||||
else:
|
||||
job.message = 'worker 已领取路径上传任务'
|
||||
db.session.commit()
|
||||
return job
|
||||
|
||||
|
||||
def process_next_kb_job() -> tuple[bool, str]:
|
||||
# 先回收历史卡死的 running 任务,再领取下一条 queued 任务
|
||||
recover_stale_running_jobs()
|
||||
|
||||
job = (
|
||||
db.session.query(KbJob)
|
||||
.filter(KbJob.job_type.in_(('path_upload', 'clean')), KbJob.status == 'queued')
|
||||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||||
.first()
|
||||
)
|
||||
job = claim_next_kb_job()
|
||||
if not job:
|
||||
return False, 'no_job'
|
||||
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job, run_sync_job
|
||||
|
||||
if job.job_type == 'path_upload':
|
||||
return run_path_upload_job(job.id)
|
||||
if job.job_type == 'sync_dify':
|
||||
return run_sync_job(job.id)
|
||||
return run_clean_job(job.id)
|
||||
|
||||
|
||||
|
||||
+36
-5
@@ -5,6 +5,7 @@ backend/worker_kb.py
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
@@ -16,12 +17,12 @@ _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')
|
||||
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(_LOG_FORMAT, datefmt=_LOG_DATEFMT))
|
||||
handler.setFormatter(logging.Formatter(f'{_LOG_FORMAT} [worker={worker_label}]', datefmt=_LOG_DATEFMT))
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
@@ -58,8 +59,9 @@ def _resolve_config_name() -> str:
|
||||
return mapping.get(env_name, 'production')
|
||||
|
||||
|
||||
def main():
|
||||
log = _configure_logging()
|
||||
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))
|
||||
|
||||
@@ -73,5 +75,34 @@ def main():
|
||||
log.info('processed job: %s', message)
|
||||
|
||||
|
||||
def main():
|
||||
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)
|
||||
return
|
||||
|
||||
log = _configure_logging('master')
|
||||
log.info('starting %s 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}')
|
||||
proc.start()
|
||||
workers.append(proc)
|
||||
|
||||
try:
|
||||
for proc in workers:
|
||||
proc.join()
|
||||
except KeyboardInterrupt:
|
||||
log.info('stopping worker pool')
|
||||
for proc in workers:
|
||||
if proc.is_alive():
|
||||
proc.terminate()
|
||||
for proc in workers:
|
||||
proc.join(timeout=5)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
mp.freeze_support()
|
||||
main()
|
||||
Reference in new issue
Block a user