feat(feishu): 添加飞书入站事件inbox和混合数据库协调功能 - 实现飞书入站事件持久化inbox机制,支持状态管理、租约锁定和重试退避 - 添加混合数据库基线协调工具,确保平台PostgreSQL结构安全对齐 - 增加运行组件心跳检测和readiness就绪检查机制 - 实现app_ticket事件的安全轮换和验证处理 - 添加生产环境运行编排和fail-closed安全机制 - 支持webhook快速确认和长连接独立进程处理 - 完善个人数据擦除时的待处理事件清理功能 ```
236 lines
8.3 KiB
Python
236 lines
8.3 KiB
Python
from hashlib import sha256
|
|
from secrets import compare_digest
|
|
from typing import Any
|
|
|
|
from fastapi import HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.constants import ActorValue
|
|
from app.core.config import get_settings
|
|
from app.modules.audit.constants import AuditAction, AuditSource
|
|
from app.modules.audit.schemas import AuditLogCreate
|
|
from app.modules.audit.service import AuditService
|
|
from app.modules.feishu.client import FeishuClient
|
|
from app.modules.feishu.constants import (
|
|
FEISHU_EMPTY_CARD_TEXT,
|
|
FEISHU_INVALID_TOKEN,
|
|
FEISHU_VERIFICATION_TOKEN_REQUIRED,
|
|
FeishuPayloadKey,
|
|
FeishuReceiveIdType,
|
|
)
|
|
from app.modules.feishu.services.reply_outbox import current_reply_outbox
|
|
|
|
|
|
class FeishuService:
|
|
"""Send Feishu messages and record audit entries for outbound actions."""
|
|
|
|
def __init__(self, db: Session, tenant_key: str | None = None):
|
|
self.db = db
|
|
self.audit = AuditService(db)
|
|
self.client = FeishuClient(db)
|
|
self.tenant_key = _optional_text(tenant_key) or _optional_text(
|
|
get_settings().feishu_default_tenant_key
|
|
)
|
|
self.message_uuid: str | None = None
|
|
|
|
def set_tenant_key(self, tenant_key: str | None) -> None:
|
|
"""Set the default tenant used by subsequent outbound operations."""
|
|
|
|
self.tenant_key = _optional_text(tenant_key)
|
|
|
|
def set_message_uuid(self, message_uuid: str | None) -> None:
|
|
"""Set the idempotency UUID used by replies in the current command."""
|
|
|
|
self.message_uuid = _optional_text(message_uuid)
|
|
|
|
def verify_event(self, payload: dict[str, Any]) -> None:
|
|
settings = get_settings()
|
|
expected = settings.feishu_verification_token
|
|
header = payload.get(FeishuPayloadKey.HEADER) or {}
|
|
token = payload.get(FeishuPayloadKey.TOKEN) or header.get(FeishuPayloadKey.TOKEN)
|
|
if not expected:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail=FEISHU_VERIFICATION_TOKEN_REQUIRED,
|
|
)
|
|
if not token or not compare_digest(str(token), expected):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail=FEISHU_INVALID_TOKEN,
|
|
)
|
|
|
|
def send_text(
|
|
self,
|
|
text: str,
|
|
receive_id: str | None = None,
|
|
receive_id_type: str = FeishuReceiveIdType.CHAT_ID,
|
|
actor: str = ActorValue.SYSTEM,
|
|
uuid: str | None = None,
|
|
tenant_key: str | None = None,
|
|
record_audit: bool = True,
|
|
) -> dict[str, Any]:
|
|
resolved_uuid = uuid or self.message_uuid
|
|
resolved_tenant_key = self._resolve_tenant_key(tenant_key)
|
|
reply_outbox = current_reply_outbox()
|
|
if reply_outbox is not None:
|
|
return reply_outbox.capture_text(
|
|
text=text,
|
|
receive_id=receive_id,
|
|
default_receive_id=get_settings().feishu_default_chat_id,
|
|
receive_id_type=receive_id_type,
|
|
actor=actor,
|
|
message_uuid=resolved_uuid,
|
|
tenant_key=resolved_tenant_key,
|
|
record_audit=record_audit,
|
|
)
|
|
result = self.client.send_text(
|
|
text,
|
|
receive_id,
|
|
receive_id_type,
|
|
resolved_uuid,
|
|
tenant_key=resolved_tenant_key,
|
|
)
|
|
if record_audit:
|
|
self.audit.log(
|
|
AuditLogCreate(
|
|
actor=actor,
|
|
source=AuditSource.FEISHU,
|
|
action=AuditAction.FEISHU_SEND_TEXT,
|
|
request_payload={
|
|
"receive_target_hash": _target_fingerprint(receive_id),
|
|
FeishuPayloadKey.RECEIVE_ID_TYPE: receive_id_type,
|
|
"content_length": len(text),
|
|
FeishuPayloadKey.UUID: resolved_uuid,
|
|
},
|
|
response_payload=result,
|
|
)
|
|
)
|
|
return result
|
|
|
|
def send_card(
|
|
self,
|
|
card: dict[str, Any],
|
|
receive_id: str | None = None,
|
|
receive_id_type: str = FeishuReceiveIdType.CHAT_ID,
|
|
actor: str = ActorValue.SYSTEM,
|
|
uuid: str | None = None,
|
|
tenant_key: str | None = None,
|
|
) -> dict[str, Any]:
|
|
resolved_uuid = uuid or self.message_uuid
|
|
resolved_tenant_key = self._resolve_tenant_key(tenant_key)
|
|
reply_outbox = current_reply_outbox()
|
|
if reply_outbox is not None:
|
|
return reply_outbox.capture_card(
|
|
card=card,
|
|
receive_id=receive_id,
|
|
default_receive_id=get_settings().feishu_default_chat_id,
|
|
receive_id_type=receive_id_type,
|
|
actor=actor,
|
|
message_uuid=resolved_uuid,
|
|
tenant_key=resolved_tenant_key,
|
|
)
|
|
result = self.client.send_card(
|
|
card,
|
|
receive_id,
|
|
receive_id_type,
|
|
resolved_uuid,
|
|
tenant_key=resolved_tenant_key,
|
|
)
|
|
self.audit.log(
|
|
AuditLogCreate(
|
|
actor=actor,
|
|
source=AuditSource.FEISHU,
|
|
action=AuditAction.FEISHU_SEND_CARD,
|
|
request_payload={
|
|
"receive_target_hash": _target_fingerprint(receive_id),
|
|
FeishuPayloadKey.RECEIVE_ID_TYPE: receive_id_type,
|
|
"card_element_count": len(card.get(FeishuPayloadKey.ELEMENTS) or []),
|
|
FeishuPayloadKey.UUID: resolved_uuid,
|
|
},
|
|
response_payload=result,
|
|
)
|
|
)
|
|
return result
|
|
|
|
def upload_image(
|
|
self,
|
|
image: bytes,
|
|
actor: str = ActorValue.SYSTEM,
|
|
tenant_key: str | None = None,
|
|
) -> dict[str, Any]:
|
|
resolved_tenant_key = self._resolve_tenant_key(tenant_key)
|
|
reply_outbox = current_reply_outbox()
|
|
if reply_outbox is not None:
|
|
return reply_outbox.capture_image(
|
|
image=image,
|
|
actor=actor,
|
|
tenant_key=resolved_tenant_key,
|
|
)
|
|
result = self.client.upload_image(
|
|
image,
|
|
tenant_key=resolved_tenant_key,
|
|
)
|
|
self.audit.log(
|
|
AuditLogCreate(
|
|
actor=actor,
|
|
source=AuditSource.FEISHU,
|
|
action=AuditAction.FEISHU_UPLOAD_IMAGE,
|
|
request_payload={"content_type": "image/png", "size": len(image)},
|
|
response_payload=result,
|
|
)
|
|
)
|
|
return result
|
|
|
|
def _resolve_tenant_key(self, tenant_key: str | None) -> str | None:
|
|
return _optional_text(tenant_key) or self.tenant_key
|
|
|
|
@staticmethod
|
|
def build_basic_card(
|
|
title: str,
|
|
lines: list[str],
|
|
image_key: str | None = None,
|
|
image_alt: str | None = None,
|
|
) -> dict[str, Any]:
|
|
elements: list[dict[str, Any]] = []
|
|
if image_key:
|
|
elements.append(
|
|
{
|
|
FeishuPayloadKey.TAG: FeishuPayloadKey.IMG,
|
|
FeishuPayloadKey.IMG_KEY: image_key,
|
|
FeishuPayloadKey.ALT: {
|
|
FeishuPayloadKey.TAG: FeishuPayloadKey.PLAIN_TEXT,
|
|
FeishuPayloadKey.CONTENT: image_alt or "生命周期数据图",
|
|
},
|
|
}
|
|
)
|
|
elements.append(
|
|
{
|
|
FeishuPayloadKey.TAG: FeishuPayloadKey.DIV,
|
|
FeishuPayloadKey.TEXT: {
|
|
FeishuPayloadKey.TAG: FeishuPayloadKey.LARK_MARKDOWN,
|
|
FeishuPayloadKey.CONTENT: "\n".join(lines) or FEISHU_EMPTY_CARD_TEXT,
|
|
},
|
|
}
|
|
)
|
|
return {
|
|
FeishuPayloadKey.CONFIG: {FeishuPayloadKey.WIDE_SCREEN_MODE: True},
|
|
FeishuPayloadKey.HEADER: {
|
|
FeishuPayloadKey.TITLE: {
|
|
FeishuPayloadKey.TAG: FeishuPayloadKey.PLAIN_TEXT,
|
|
FeishuPayloadKey.CONTENT: title,
|
|
}
|
|
},
|
|
FeishuPayloadKey.ELEMENTS: elements,
|
|
}
|
|
|
|
|
|
def _target_fingerprint(receive_id: str | None) -> str | None:
|
|
if not receive_id:
|
|
return None
|
|
return sha256(receive_id.encode("utf-8")).hexdigest()[:16]
|
|
|
|
|
|
def _optional_text(value: str | None) -> str | None:
|
|
text = str(value or "").strip()
|
|
return text or None
|