2026-06-01 14:39:45 +08:00
|
|
|
package haiyuapi
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"context"
|
|
|
|
|
"crypto/md5"
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
|
|
|
|
"net/http"
|
|
|
|
|
"strconv"
|
|
|
|
|
"strings"
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"tyapi-server/internal/shared/external_logger"
|
|
|
|
|
)
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
const (
|
|
|
|
|
defaultRequestTimeout = 60 * time.Second
|
|
|
|
|
maxLogParamValueLen = 300
|
|
|
|
|
maxLogResponseBodyLen = 500
|
|
|
|
|
)
|
2026-06-01 14:39:45 +08:00
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
// HaiyuapiConfig 海宇 API 服务配置
|
|
|
|
|
type HaiyuapiConfig struct {
|
2026-06-01 14:39:45 +08:00
|
|
|
BaseURL string
|
|
|
|
|
AccessID string
|
|
|
|
|
SecretKey string
|
|
|
|
|
Timeout time.Duration
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
// HaiyuapiService 海宇平台中转服务
|
2026-06-01 14:39:45 +08:00
|
|
|
type HaiyuapiService struct {
|
2026-07-05 00:48:37 +08:00
|
|
|
config HaiyuapiConfig
|
2026-06-01 14:39:45 +08:00
|
|
|
logger *external_logger.ExternalServiceLogger
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
// NewHaiyuapiService 创建海宇 API 服务实例
|
|
|
|
|
func NewHaiyuapiService(cfg HaiyuapiConfig, logger *external_logger.ExternalServiceLogger) *HaiyuapiService {
|
|
|
|
|
if cfg.Timeout == 0 {
|
|
|
|
|
cfg.Timeout = defaultRequestTimeout
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
return &HaiyuapiService{
|
2026-07-05 00:48:37 +08:00
|
|
|
config: cfg,
|
2026-06-01 14:39:45 +08:00
|
|
|
logger: logger,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
func (s *HaiyuapiService) generateRequestID() string {
|
|
|
|
|
timestamp := time.Now().UnixNano()
|
|
|
|
|
hash := md5.Sum([]byte(fmt.Sprintf("%d_%s", timestamp, s.config.AccessID)))
|
|
|
|
|
return fmt.Sprintf("haiyuapi_%x", hash[:8])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func truncateForLog(str string, maxLen int) string {
|
|
|
|
|
if maxLen <= 0 || len(str) <= maxLen {
|
|
|
|
|
return str
|
|
|
|
|
}
|
|
|
|
|
return str[:maxLen] + "...[truncated, total " + strconv.Itoa(len(str)) + " chars]"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func requestParamsForLog(params map[string]interface{}) map[string]interface{} {
|
|
|
|
|
if params == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
out := make(map[string]interface{}, len(params))
|
|
|
|
|
for k, v := range params {
|
|
|
|
|
if v == nil {
|
|
|
|
|
out[k] = nil
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
switch val := v.(type) {
|
|
|
|
|
case string:
|
|
|
|
|
out[k] = truncateForLog(val, maxLogParamValueLen)
|
|
|
|
|
default:
|
|
|
|
|
out[k] = truncateForLog(fmt.Sprint(v), maxLogParamValueLen)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return out
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// CallAPI 调用海宇平台指定产品(产品编号与处理器 ApiCode 一致)
|
|
|
|
|
func (s *HaiyuapiService) CallAPI(ctx context.Context, productCode string, params map[string]interface{}) ([]byte, error) {
|
2026-06-01 14:39:45 +08:00
|
|
|
startTime := time.Now()
|
2026-07-05 00:48:37 +08:00
|
|
|
requestID := s.generateRequestID()
|
2026-06-01 14:39:45 +08:00
|
|
|
|
|
|
|
|
var transactionID string
|
|
|
|
|
if id, ok := ctx.Value("transaction_id").(string); ok {
|
|
|
|
|
transactionID = id
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
baseURL := strings.TrimSuffix(s.config.BaseURL, "/")
|
2026-06-01 14:39:45 +08:00
|
|
|
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
2026-07-05 00:48:37 +08:00
|
|
|
reqURL := fmt.Sprintf("%s/api/v1/%s?t=%s", baseURL, productCode, timestamp)
|
2026-06-01 14:39:45 +08:00
|
|
|
|
|
|
|
|
if s.logger != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
s.logger.LogRequest(requestID, transactionID, productCode, reqURL)
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
encryptedData, err := EncryptParams(params, s.config.SecretKey)
|
|
|
|
|
if err != nil {
|
|
|
|
|
err = errors.Join(ErrSystem, fmt.Errorf("请求加密失败: %w", err))
|
|
|
|
|
if s.logger != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{"request_params": requestParamsForLog(params)})
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bodyBytes, err := json.Marshal(RequestPayload{Data: encryptedData})
|
|
|
|
|
if err != nil {
|
|
|
|
|
err = errors.Join(ErrSystem, err)
|
|
|
|
|
if s.logger != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{"request_params": requestParamsForLog(params)})
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(bodyBytes))
|
2026-06-01 14:39:45 +08:00
|
|
|
if err != nil {
|
|
|
|
|
err = errors.Join(ErrSystem, err)
|
|
|
|
|
if s.logger != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{"request_params": requestParamsForLog(params)})
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
req.Header.Set(HeaderContentType, ContentTypeJSON)
|
|
|
|
|
req.Header.Set(HeaderAccessID, s.config.AccessID)
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
client := &http.Client{Timeout: s.config.Timeout}
|
|
|
|
|
resp, err := client.Do(req)
|
2026-06-01 14:39:45 +08:00
|
|
|
if err != nil {
|
|
|
|
|
err = wrapHTTPError(err)
|
|
|
|
|
if s.logger != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{"request_params": requestParamsForLog(params)})
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
duration := time.Since(startTime)
|
|
|
|
|
raw, err := io.ReadAll(resp.Body)
|
2026-06-01 14:39:45 +08:00
|
|
|
if err != nil {
|
|
|
|
|
err = errors.Join(ErrSystem, err)
|
|
|
|
|
if s.logger != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{"request_params": requestParamsForLog(params)})
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
2026-07-05 00:48:37 +08:00
|
|
|
err = errors.Join(ErrDatasource, fmt.Errorf("HTTP %d", resp.StatusCode))
|
2026-06-01 14:39:45 +08:00
|
|
|
if s.logger != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{
|
|
|
|
|
"request_params": requestParamsForLog(params),
|
|
|
|
|
"response_body": truncateForLog(string(raw), maxLogResponseBodyLen),
|
|
|
|
|
})
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
if s.logger != nil {
|
|
|
|
|
s.logger.LogResponse(requestID, transactionID, productCode, resp.StatusCode, duration)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var outer APIResponse
|
|
|
|
|
if err := json.Unmarshal(raw, &outer); err != nil {
|
|
|
|
|
parseErr := errors.Join(ErrSystem, fmt.Errorf("响应解析失败: %w", err))
|
2026-06-01 14:39:45 +08:00
|
|
|
if s.logger != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
s.logger.LogError(requestID, transactionID, productCode, parseErr, map[string]interface{}{
|
|
|
|
|
"request_params": requestParamsForLog(params),
|
|
|
|
|
"response_body": truncateForLog(string(raw), maxLogResponseBodyLen),
|
|
|
|
|
})
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
2026-07-05 00:48:37 +08:00
|
|
|
return nil, parseErr
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
if outer.Code != CodeSuccess {
|
|
|
|
|
mappedErr := mapBusinessError(outer.Code, outer.Message)
|
2026-06-01 14:39:45 +08:00
|
|
|
if s.logger != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
s.logger.LogError(requestID, transactionID, productCode, mappedErr, map[string]interface{}{
|
|
|
|
|
"request_params": requestParamsForLog(params),
|
|
|
|
|
"response_body": truncateForLog(string(raw), maxLogResponseBodyLen),
|
|
|
|
|
"api_code": outer.Code,
|
|
|
|
|
})
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
2026-07-05 00:48:37 +08:00
|
|
|
if errors.Is(mappedErr, ErrNotFound) {
|
|
|
|
|
return nil, mappedErr
|
|
|
|
|
}
|
|
|
|
|
return nil, mappedErr
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
plain, err := DecryptData(outer.Data, s.config.SecretKey)
|
2026-06-01 14:39:45 +08:00
|
|
|
if err != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
decErr := errors.Join(ErrSystem, fmt.Errorf("解密响应失败: %w", err))
|
2026-06-01 14:39:45 +08:00
|
|
|
if s.logger != nil {
|
2026-07-05 00:48:37 +08:00
|
|
|
s.logger.LogError(requestID, transactionID, productCode, decErr, map[string]interface{}{
|
|
|
|
|
"request_params": requestParamsForLog(params),
|
|
|
|
|
"response_body": truncateForLog(string(raw), maxLogResponseBodyLen),
|
|
|
|
|
})
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
2026-07-05 00:48:37 +08:00
|
|
|
return nil, decErr
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
if len(plain) == 0 {
|
|
|
|
|
return []byte("{}"), nil
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
2026-07-05 00:48:37 +08:00
|
|
|
if !json.Valid(plain) {
|
|
|
|
|
return plain, nil
|
|
|
|
|
}
|
|
|
|
|
return plain, nil
|
|
|
|
|
}
|
2026-06-01 14:39:45 +08:00
|
|
|
|
2026-07-05 00:48:37 +08:00
|
|
|
func mapBusinessError(code int, message string) error {
|
|
|
|
|
switch code {
|
|
|
|
|
case CodeSuccess:
|
|
|
|
|
return nil
|
|
|
|
|
case CodeQueryEmpty:
|
|
|
|
|
if message != "" {
|
|
|
|
|
return errors.Join(ErrNotFound, errors.New(message))
|
|
|
|
|
}
|
|
|
|
|
return ErrNotFound
|
|
|
|
|
case CodeRequestParam:
|
|
|
|
|
if message != "" {
|
|
|
|
|
return errors.Join(ErrSystem, errors.New(message))
|
|
|
|
|
}
|
|
|
|
|
return errors.Join(ErrSystem, errors.New("请求参数结构不正确"))
|
|
|
|
|
case CodeSystem, CodeDecryptFail:
|
|
|
|
|
if message != "" {
|
|
|
|
|
return errors.Join(ErrSystem, errors.New(message))
|
|
|
|
|
}
|
|
|
|
|
return ErrSystem
|
|
|
|
|
case CodeInvalidIP, CodeMissingAccessID, CodeInvalidAccessID,
|
|
|
|
|
CodeInsufficientBalance, CodeProductNotSubscribed, CodeBusiness:
|
|
|
|
|
if message != "" {
|
|
|
|
|
return errors.Join(ErrDatasource, errors.New(message))
|
|
|
|
|
}
|
|
|
|
|
return ErrDatasource
|
|
|
|
|
default:
|
|
|
|
|
if message != "" {
|
|
|
|
|
return errors.Join(ErrDatasource, errors.New(message))
|
|
|
|
|
}
|
|
|
|
|
return ErrDatasource
|
|
|
|
|
}
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func wrapHTTPError(err error) error {
|
|
|
|
|
if err == context.DeadlineExceeded {
|
|
|
|
|
return errors.Join(ErrDatasource, err)
|
|
|
|
|
}
|
|
|
|
|
if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
|
|
|
|
|
return errors.Join(ErrDatasource, err)
|
|
|
|
|
}
|
2026-07-05 00:48:37 +08:00
|
|
|
es := err.Error()
|
|
|
|
|
if strings.Contains(es, "deadline exceeded") || strings.Contains(es, "timeout") || strings.Contains(es, "canceled") {
|
2026-06-01 14:39:45 +08:00
|
|
|
return errors.Join(ErrDatasource, err)
|
|
|
|
|
}
|
2026-07-05 00:48:37 +08:00
|
|
|
return errors.Join(ErrSystem, err)
|
2026-06-01 14:39:45 +08:00
|
|
|
}
|