fix(platform): API 调用日志截断对齐 UTF-8 字符边界 - 防止截断报文写库失败导致订单误标 uncertain (#695)

truncateAPICallPayload 原先按字节硬切超长报文,切点多字节字符时会产生
非法 UTF-8,写 PostgreSQL 报 invalid byte sequence,调用日志入库失败并
连锁导致订单被标为 uncertain。

- 截断点回退到最近的 UTF-8 字符边界
- 对源报文本身的非法字节做 strings.ToValidUTF8 兜底
- 补充回归测试:中文/emoji/中日韩混排/非法字节等场景

Co-authored-by: xiaomuclaw <282836183+xiaomuclaw@users.noreply.github.com>
This commit is contained in:
xiaomuclaw
2026-10-06 09:28:17 +08:00
committed by GitHub
parent 25b1aac165
commit fb101b76d0
2 changed files with 72 additions and 1 deletions

View File

@@ -11,6 +11,7 @@ import (
"net/http"
"net/url"
"strings"
"unicode/utf8"
)
const maxAPICallPayloadBytes = 128 << 10
@@ -151,5 +152,14 @@ func truncateAPICallPayload(value string) string {
if len(value) <= maxAPICallPayloadBytes {
return value
}
return value[:maxAPICallPayloadBytes] + fmt.Sprintf("\n[报文已截断,原始长度 %d 字节]", len(value))
cut := maxAPICallPayloadBytes
for cut > 0 && !utf8.RuneStart(value[cut]) {
cut--
}
// 上游报文不保证是合法 UTF-8,直接入库会被 PostgreSQL 以 invalid byte sequence 拒收。
truncated := value[:cut]
if !utf8.ValidString(truncated) {
truncated = strings.ToValidUTF8(truncated, string(utf8.RuneError))
}
return truncated + fmt.Sprintf("\n[报文已截断,原始长度 %d 字节]", len(value))
}