Merge branch 'dev' of https://gitee.com/justop/hxops into dev

This commit is contained in:
runny committed 2026-05-20 16:06:36 +08:00
commit 40c80eaacb
3 files changed
+193 -14

No files matched your search

Vendored
+141
View File
@@ -1,3 +1,84 @@
import groovy.json.JsonOutput
// 企业微信群机器人部署通知(成功/失败/中止)。Webhook 完整 URL 存 Jenkins 凭据 WECOM_WEBHOOK_DEPLOY,勿写入 Git。
// WeCom group-bot deploy notifications. Store webhook URL in Jenkins Secret text credential only.
def notifyWecomDeploy(Map opts) {
if ((env.DISABLE_DEPLOY_WECOM_NOTIFY ?: '').equalsIgnoreCase('true')) {
echo '[WeCom] DISABLE_DEPLOY_WECOM_NOTIFY=true,跳过通知'
return
}
def credId = (opts.webhookCredId ?: env.WECOM_WEBHOOK_CRED ?: 'WECOM_WEBHOOK_DEPLOY').trim()
def envLabel = opts.envLabel ?: '部署环境'
def host = opts.host ?: '-'
def status = (opts.status ?: 'success').toString().toLowerCase()
def isSuccess = status == 'success'
def extraNote = (opts.extraNote ?: '').trim()
try {
withCredentials([string(credentialsId: credId, variable: 'WECOM_WEBHOOK_URL')]) {
def webhookUrl = WECOM_WEBHOOK_URL?.trim()
if (!webhookUrl) {
echo "[WeCom] 凭据 ${credId} 为空,跳过通知"
return
}
def shortCommit = env.GIT_COMMIT ? env.GIT_COMMIT.take(8) : '-'
def buildLink = env.BUILD_URL ?: '-'
def title = isSuccess ? "✅ ${envLabel} 部署成功" : "❌ ${envLabel} 部署失败"
def lines = [
"## ${title}",
"> **分支**: ${env.BRANCH_NAME ?: '-'}",
"> **提交**: `${shortCommit}`",
"> **目标主机**: ${host}",
"> **构建**: [#${env.BUILD_NUMBER}](${buildLink})",
"> **变更**: 前端=${env.FRONTEND_CHANGED ?: '-'} 后端=${env.BACKEND_CHANGED ?: '-'} 配置=${env.DEPLOY_CONFIG_CHANGED ?: '-'}",
]
if (env.FORCE_FULL_DEPLOY_USED == 'true') {
lines << '> **备注**: 强制全量部署'
}
if (env.REMOTE_DRIFT_DETECTED == 'true') {
lines << '> **备注**: 远端版本漂移触发部署'
}
if (extraNote) {
lines << "> **说明**: ${extraNote}"
}
if (!isSuccess) {
lines << '> **处理**: 请打开 Jenkins 构建日志排查失败步骤'
}
def payload = [
msgtype: 'markdown',
markdown: [content: lines.join('\n')],
]
writeFile(file: 'wecom-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
def httpCode = sh(
returnStdout: true,
script: '''
set +e
code=$(curl -sS -o wecom-notify-response.txt -w "%{http_code}" \
-X POST "$WECOM_WEBHOOK_URL" \
-H "Content-Type: application/json" \
-d @wecom-notify-payload.json)
echo "[WeCom] HTTP ${code}" >&2
cat wecom-notify-response.txt >&2 || true
echo "${code}"
'''
).trim()
def resp = readFile('wecom-notify-response.txt').trim()
if (httpCode == '200' && resp.contains('"errcode":0')) {
echo '[WeCom] 通知已发送'
} else {
echo "[WeCom] 发送可能失败,HTTP=${httpCode},响应=${resp}"
}
}
} catch (Exception e) {
echo "[WeCom] 通知发送异常(不影响构建结果): ${e.message}"
}
}
pipeline {
agent any
@@ -242,6 +323,36 @@ pipeline {
}
echo "[Deploy Test] done"
}
post {
success {
script {
notifyWecomDeploy(
envLabel: '测试环境',
host: env.TEST_DEPLOY_HOST,
status: 'success',
)
}
}
failure {
script {
notifyWecomDeploy(
envLabel: '测试环境',
host: env.TEST_DEPLOY_HOST,
status: 'failure',
)
}
}
aborted {
script {
notifyWecomDeploy(
envLabel: '测试环境',
host: env.TEST_DEPLOY_HOST,
status: 'failure',
extraNote: '阶段已中止(可能为人工取消)',
)
}
}
}
}
stage('Deploy Prod') {
@@ -301,6 +412,36 @@ pipeline {
}
echo "[Deploy Prod] done"
}
post {
success {
script {
notifyWecomDeploy(
envLabel: '生产环境',
host: env.PROD_DEPLOY_HOST,
status: 'success',
)
}
}
failure {
script {
notifyWecomDeploy(
envLabel: '生产环境',
host: env.PROD_DEPLOY_HOST,
status: 'failure',
)
}
}
aborted {
script {
notifyWecomDeploy(
envLabel: '生产环境',
host: env.PROD_DEPLOY_HOST,
status: 'failure',
extraNote: '阶段已中止(可能为未确认生产部署或人工取消)',
)
}
}
}
}
}
+5 -2
View File
@@ -11,6 +11,7 @@ import mimetypes
import tempfile
import os
import subprocess
import uuid
from urllib.parse import urlparse
import requests
@@ -738,13 +739,15 @@ def chat_completions():
conversation_id = data.get('conversation_id')
# 知识库类型
kb_type = data.get('kb_type', '企业知识库')
request_id = uuid.uuid4().hex[:12]
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
current_app.logger.info(
"[chat-api] /completions request user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s",
"[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s",
request_id,
getattr(user, 'id', None),
getattr(agent, 'id', None),
len(query or ''),
@@ -776,7 +779,7 @@ def chat_completions():
if HRLeaveSQLServerService.supports(query):
generator = HRLeaveSQLServerService.stream_chat(query, user, agent, conversation_id)
else:
generator = DifyService.stream_chat(query, user.id, agent, conversation_id)
generator = DifyService.stream_chat(query, user.id, agent, conversation_id, request_id=request_id)
# 返回 SSE 响应,mimetype 设为 text/event-stream
return Response(
+47 -12
View File
@@ -23,6 +23,7 @@ chat.py (/api/chat/completions)
-> yield SSE events to frontend
"""
import json
import os
import time
import uuid
from typing import Any, List, Optional
@@ -37,6 +38,7 @@ from app.services.integration_api import IntegrationApiService
class DifyService:
"""Dify service wrapper."""
VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on")
@staticmethod
def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
@@ -290,7 +292,7 @@ class DifyService:
return {}
@staticmethod
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, request_id: str | None = None):
"""
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
Stream chat completion from Dify and relay SSE events to caller.
@@ -329,7 +331,8 @@ class DifyService:
if current_app:
current_app.logger.info(
"[chat-stream] start user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
"[chat-stream] start request_id=%s user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
request_id,
user_id,
getattr(agent, 'id', None),
base_url,
@@ -338,6 +341,9 @@ class DifyService:
)
start_time = time.time()
first_token_at: float | None = None
message_count = 0
event_count = 0
full_answer: List[str] = []
retriever_resources: List[Any] = []
attribution_parts: List[str] = []
@@ -348,7 +354,8 @@ class DifyService:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
if current_app:
current_app.logger.info(
"[chat-stream] dify response status=%s reason=%s attempt=%s",
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
request_id,
response.status_code,
response.reason,
attempt,
@@ -360,7 +367,8 @@ class DifyService:
except Exception:
error_body = "<failed to read response body>"
current_app.logger.error(
"[chat-stream] dify bad response status=%s url=%s attempt=%s body=%s",
"[chat-stream] dify bad response request_id=%s status=%s url=%s attempt=%s body=%s",
request_id,
response.status_code,
url,
attempt,
@@ -386,9 +394,13 @@ class DifyService:
continue
event = data.get('event')
if current_app:
current_app.logger.info(
"[chat-stream] event=%s answer_len=%s has_metadata=%s conversation_id=%s",
event_count += 1
# Keep stream event logs behind an explicit switch to prevent
# flooding when global logger level is DEBUG.
if DifyService.VERBOSE_STREAM_LOG and current_app:
current_app.logger.debug(
"[chat-stream] event request_id=%s event=%s answer_len=%s has_metadata=%s conversation_id=%s",
request_id,
event,
len(data.get('answer', '') or ''),
bool(data.get('metadata')),
@@ -396,6 +408,16 @@ class DifyService:
)
if event == 'message':
message_count += 1
if first_token_at is None:
first_token_at = time.time()
if current_app:
current_app.logger.info(
"[chat-perf] first-token request_id=%s ttft_ms=%s attempt=%s",
request_id,
int((first_token_at - start_time) * 1000),
attempt,
)
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
@@ -405,12 +427,15 @@ class DifyService:
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'message_end':
message_end_started = time.time()
if current_app:
current_app.logger.info(
"[source-link] message_end: collected retriever resources=%s",
"[source-link] message_end request_id=%s collected retriever_resources=%s",
request_id,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
enrich_done_at = time.time()
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
@@ -420,6 +445,7 @@ class DifyService:
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
@@ -432,23 +458,32 @@ class DifyService:
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
db_write_done_at = time.time()
if chat_log_id:
data['chat_log_id'] = chat_log_id
if current_app:
current_app.logger.info(
"[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s",
data.get('conversation_id') or normalized_conversation_id,
"[chat-perf] summary request_id=%s total_ms=%s ttft_ms=%s stream_ms=%s postprocess_ms=%s enrich_ms=%s db_write_ms=%s events=%s message_events=%s answer_len=%s resources=%s attribution=%s conversation_id=%s",
request_id,
latency,
int((first_token_at - start_time) * 1000) if first_token_at else None,
int((message_end_started - first_token_at) * 1000) if first_token_at else None,
int((time.time() - message_end_started) * 1000),
int((enrich_done_at - message_end_started) * 1000),
int((db_write_done_at - db_write_started) * 1000),
event_count,
message_count,
len(''.join(full_answer)),
len(retriever_resources),
len(attribution_parts),
latency,
data.get('conversation_id') or normalized_conversation_id,
)
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
break
except requests.exceptions.RequestException as e:
if current_app:
current_app.logger.exception("[chat-stream] request exception attempt=%s: %s", attempt, e)
current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e)
if attempt < max_retries:
time.sleep(attempt * 2)
continue