refactor(backend): dify, minio等迁移到integration,清除无效文件
This commit is contained in:
1 parent
7fe7a39384
commit
faa554ade4
90 files changed
+7540
-9649
No files matched your search
@@ -1,8 +1,514 @@
|
||||
"""
|
||||
backend/app/services/integrations/integration_api.py
|
||||
|
||||
用途:知识库源文件反查等集成 API 适配。
|
||||
用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。
|
||||
依赖:Flask current_app、core.http_context、requests、Kb* 模型。
|
||||
逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。
|
||||
"""
|
||||
from app.services import integration_api # noqa: F401
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from urllib.parse import urlparse
|
||||
|
||||
__all__ = ['integration_api']
|
||||
import requests
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
from app.core.config.settings import Config
|
||||
from app.core.http_context import has_http_request, header, host_url
|
||||
|
||||
|
||||
class IntegrationApiService:
|
||||
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _request_origin_url() -> str:
|
||||
if not has_http_request():
|
||||
return ""
|
||||
|
||||
forwarded_proto = header("X-Forwarded-Proto").split(",")[0].strip()
|
||||
forwarded_host = header("X-Forwarded-Host").split(",")[0].strip()
|
||||
if forwarded_proto and forwarded_host:
|
||||
return f"{forwarded_proto}://{forwarded_host}".rstrip("/")
|
||||
|
||||
origin = header("Origin").strip().rstrip("/")
|
||||
if origin:
|
||||
return origin
|
||||
|
||||
referer = header("Referer").strip()
|
||||
if referer:
|
||||
parsed = urlparse(referer)
|
||||
if parsed.scheme and parsed.netloc:
|
||||
return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
|
||||
|
||||
return host_url()
|
||||
|
||||
@staticmethod
|
||||
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
|
||||
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
|
||||
"""
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
try:
|
||||
service = KbDifySyncService()
|
||||
if not service.base_url or not service.api_key:
|
||||
return None
|
||||
|
||||
document_payload = service.get_document(
|
||||
dataset_id=str(dataset_id),
|
||||
document_id=str(remote_document_id),
|
||||
)
|
||||
if not isinstance(document_payload, dict):
|
||||
return None
|
||||
|
||||
download_resp = requests.get(
|
||||
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
|
||||
headers=service._headers(),
|
||||
timeout=(5, 15),
|
||||
)
|
||||
if download_resp.status_code != 200:
|
||||
if has_app_context():
|
||||
current_app.logger.info(
|
||||
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
download_resp.status_code,
|
||||
)
|
||||
return None
|
||||
|
||||
download_payload = download_resp.json() if download_resp.content else {}
|
||||
source_url = str((download_payload or {}).get("url") or "").strip()
|
||||
if not source_url:
|
||||
return None
|
||||
|
||||
upload_info = (
|
||||
((document_payload.get("data_source_info") or {}).get("upload_file"))
|
||||
if isinstance(document_payload.get("data_source_info"), dict)
|
||||
else {}
|
||||
) or {}
|
||||
source_filename = str(
|
||||
upload_info.get("name")
|
||||
or document_payload.get("name")
|
||||
or ""
|
||||
).strip() or None
|
||||
source_ext = str(
|
||||
upload_info.get("extension")
|
||||
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
|
||||
).strip().lower() or None
|
||||
|
||||
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
|
||||
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
|
||||
|
||||
return {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": source_filename,
|
||||
"source_ext": source_ext,
|
||||
"download_url_expires_at": expires_at,
|
||||
"version_id": None,
|
||||
"document_id": remote_document_id,
|
||||
}
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(
|
||||
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
e,
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
|
||||
if not isinstance(row, dict):
|
||||
return None
|
||||
req = row.get("request") if isinstance(row.get("request"), dict) else {}
|
||||
dataset_id = str(req.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(req.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id or not row.get("found"):
|
||||
return None
|
||||
|
||||
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
|
||||
source_url = doc.get("source_download_url")
|
||||
if not source_url:
|
||||
return None
|
||||
|
||||
normalized = {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": doc.get("source_filename"),
|
||||
"source_ext": doc.get("source_ext"),
|
||||
"download_url_expires_at": doc.get("download_url_expires_at"),
|
||||
"version_id": doc.get("version_id"),
|
||||
"document_id": doc.get("document_id"),
|
||||
}
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
return key, normalized
|
||||
|
||||
@staticmethod
|
||||
def _is_loopback_url(url: str) -> bool:
|
||||
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
|
||||
return host in {"127.0.0.1", "localhost", "::1"}
|
||||
|
||||
@staticmethod
|
||||
def get_api_key() -> str:
|
||||
if has_app_context():
|
||||
return str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
return str(Config.INTEGRATION_API_KEY or "").strip()
|
||||
|
||||
@staticmethod
|
||||
def get_base_url() -> str:
|
||||
mode = "local"
|
||||
if has_app_context():
|
||||
mode = str(current_app.config.get("INTEGRATION_API_MODE") or "local").strip().lower()
|
||||
configured = str(current_app.config.get("INTEGRATION_API_BASE") or "").strip().rstrip("/")
|
||||
public_base = str(current_app.config.get("WECOM_PUBLIC_BASE_URL") or "").strip().rstrip("/")
|
||||
else:
|
||||
mode = str(getattr(Config, "INTEGRATION_API_MODE", "local") or "local").strip().lower()
|
||||
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
|
||||
public_base = ""
|
||||
|
||||
# 服务端查询优先使用显式配置的集成服务地址;
|
||||
# 回退到当前请求 host 会错误地打到本后端自身。
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
if mode != "external":
|
||||
request_origin = IntegrationApiService._request_origin_url()
|
||||
if request_origin:
|
||||
return request_origin
|
||||
if public_base:
|
||||
return public_base
|
||||
if has_http_request():
|
||||
return host_url()
|
||||
|
||||
return configured
|
||||
|
||||
@staticmethod
|
||||
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
|
||||
return (str(dataset_id), str(remote_document_id))
|
||||
|
||||
@staticmethod
|
||||
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
|
||||
exp_str = payload.get("download_url_expires_at")
|
||||
if exp_str:
|
||||
try:
|
||||
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查
|
||||
source_url = payload.get("source_download_url") or ""
|
||||
if "token=" in source_url:
|
||||
try:
|
||||
import base64
|
||||
import json
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
import time
|
||||
qs = parse_qs(urlparse(source_url).query)
|
||||
if 'token' in qs:
|
||||
token = qs['token'][0]
|
||||
parts = token.split('.')
|
||||
if len(parts) >= 2:
|
||||
payload_b64 = parts[1]
|
||||
payload_b64 += '=' * (-len(payload_b64) % 4)
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
|
||||
exp = payload_data.get('exp', 0)
|
||||
if exp and exp < time.time() + 300:
|
||||
return False # 已过期或即将过期
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
从本地 KbDifySyncRecord 反查可预览下载链接。
|
||||
核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown;
|
||||
两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。
|
||||
"""
|
||||
if not has_app_context():
|
||||
return None
|
||||
from pathlib import Path
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
|
||||
|
||||
normalized_dataset_id = str(dataset_id or '').strip()
|
||||
normalized_remote_document_id = str(remote_document_id or '').strip()
|
||||
if not normalized_dataset_id or not normalized_remote_document_id:
|
||||
return None
|
||||
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.filter(
|
||||
KbDocument.is_deleted.is_(False),
|
||||
KbDifySyncRecord.dataset_id == normalized_dataset_id,
|
||||
KbDifySyncRecord.remote_document_id == normalized_remote_document_id,
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not record or not record.document_version or not record.document_version.document:
|
||||
return None
|
||||
|
||||
version = record.document_version
|
||||
document = version.document
|
||||
|
||||
def _existing(path_value: str | None):
|
||||
if not path_value:
|
||||
return None
|
||||
raw = Path(str(path_value))
|
||||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||
candidate = (raw if raw.is_absolute() else (root / raw)).resolve()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
if candidate.exists() and candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
source_path = _existing(version.source_file_path)
|
||||
markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path)
|
||||
if source_path is None and markdown_path is None:
|
||||
current_app.logger.info(
|
||||
'[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s',
|
||||
document.id,
|
||||
version.id,
|
||||
)
|
||||
return None
|
||||
|
||||
base_url = IntegrationApiService._request_origin_url()
|
||||
if not base_url:
|
||||
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||||
if explicit:
|
||||
base_url = explicit
|
||||
elif has_http_request():
|
||||
base_url = host_url()
|
||||
else:
|
||||
base_url = ''
|
||||
|
||||
import time
|
||||
import jwt
|
||||
|
||||
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
if not secret:
|
||||
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||||
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
|
||||
payload = {
|
||||
'dataset_id': normalized_dataset_id,
|
||||
'remote_document_id': normalized_remote_document_id,
|
||||
'version_id': version.id,
|
||||
'exp': exp
|
||||
}
|
||||
token = jwt.encode(payload, secret, algorithm='HS256')
|
||||
|
||||
if source_path is not None:
|
||||
kind = 'source'
|
||||
source_filename = version.source_file_name
|
||||
source_ext = version.source_file_ext
|
||||
else:
|
||||
kind = 'md'
|
||||
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
|
||||
source_filename = f'{stem}.md'
|
||||
source_ext = 'md'
|
||||
|
||||
source_download_url = (
|
||||
f'{base_url}/api/integration/files/{document.id}/download'
|
||||
f'?kind={kind}&version_id={version.id}&token={token}'
|
||||
)
|
||||
|
||||
return {
|
||||
"source_download_url": source_download_url,
|
||||
"source_filename": source_filename,
|
||||
"source_ext": source_ext,
|
||||
"download_url_expires_at": None,
|
||||
"version_id": version.id,
|
||||
"document_id": document.id,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
|
||||
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
cached = IntegrationApiService._cache.get(cache_key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
return cached
|
||||
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
if not base_url or not api_key:
|
||||
return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
|
||||
url = f"{base_url}/api/integration/dify-file"
|
||||
headers = {"X-Integration-Key": api_key}
|
||||
params = {
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
|
||||
try:
|
||||
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
if isinstance(payload, dict):
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
elif has_app_context():
|
||||
current_app.logger.info(
|
||||
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
resp.status_code,
|
||||
)
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API lookup failed: {e}")
|
||||
|
||||
batch_url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
batch_headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
batch_body = {
|
||||
"items": [
|
||||
{
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
]
|
||||
}
|
||||
try:
|
||||
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if isinstance(data, list):
|
||||
for row in data:
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
if key == cache_key:
|
||||
return normalized
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
|
||||
|
||||
# Fallback to local database if remote integration API fails or misses
|
||||
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
if local_result:
|
||||
IntegrationApiService._cache[cache_key] = local_result
|
||||
return local_result
|
||||
|
||||
# 最终兜底:直接查 Dify 文档 API 并请求签名下载 URL。
|
||||
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
|
||||
if dify_result:
|
||||
IntegrationApiService._cache[cache_key] = dify_result
|
||||
return dify_result
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
|
||||
"""
|
||||
Batch resolve source files by (dataset_id, remote_document_id).
|
||||
Returns a mapping keyed by (dataset_id, remote_document_id).
|
||||
"""
|
||||
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
if not items:
|
||||
return results
|
||||
|
||||
unresolved: List[Dict[str, str]] = []
|
||||
seen = set()
|
||||
|
||||
for item in items:
|
||||
dataset_id = str(item.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(item.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
continue
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
cached = IntegrationApiService._cache.get(key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
results[key] = cached
|
||||
else:
|
||||
unresolved.append({
|
||||
"dataset_id": dataset_id,
|
||||
"remote_document_id": remote_document_id,
|
||||
})
|
||||
|
||||
if not unresolved:
|
||||
return results
|
||||
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
if not base_url or not api_key:
|
||||
return results
|
||||
|
||||
url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
body = {"items": unresolved}
|
||||
|
||||
try:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
|
||||
if resp.status_code != 200:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(
|
||||
"Integration API batch lookup failed: status=%s", resp.status_code
|
||||
)
|
||||
else:
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if isinstance(data, list):
|
||||
for row in data:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
results[key] = normalized
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
|
||||
|
||||
# Fallback to single lookup or local DB for unresolved items
|
||||
for item in unresolved:
|
||||
dataset_id = item["dataset_id"]
|
||||
remote_document_id = item["remote_document_id"]
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
if key in results:
|
||||
continue
|
||||
|
||||
# Check if single lookup was not called already (if it was, it might be cached)
|
||||
# Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
|
||||
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
if local_result:
|
||||
IntegrationApiService._cache[key] = local_result
|
||||
results[key] = local_result
|
||||
continue
|
||||
|
||||
# As a last resort, try remote single lookup if batch missed it
|
||||
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if payload:
|
||||
results[key] = payload
|
||||
|
||||
return results
|
||||
Reference in new issue
Block a user