add QCXG7K2N
This commit is contained in:
@@ -1,13 +1,11 @@
|
||||
package haiyuapi
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"tyapi-server/internal/config"
|
||||
"tyapi-server/internal/shared/external_logger"
|
||||
)
|
||||
|
||||
// NewHaiyuapiServiceWithConfig 使用配置创建海宇API服务
|
||||
// NewHaiyuapiServiceWithConfig 使用配置创建海宇 API 服务
|
||||
func NewHaiyuapiServiceWithConfig(cfg *config.Config) (*HaiyuapiService, error) {
|
||||
loggingConfig := external_logger.ExternalServiceLoggingConfig{
|
||||
Enabled: cfg.Haiyuapi.Logging.Enabled,
|
||||
@@ -17,48 +15,35 @@ func NewHaiyuapiServiceWithConfig(cfg *config.Config) (*HaiyuapiService, error)
|
||||
EnableLevelSeparation: cfg.Haiyuapi.Logging.EnableLevelSeparation,
|
||||
LevelConfigs: make(map[string]external_logger.ExternalServiceLevelFileConfig),
|
||||
}
|
||||
|
||||
for level, levelCfg := range cfg.Haiyuapi.Logging.LevelConfigs {
|
||||
loggingConfig.LevelConfigs[level] = external_logger.ExternalServiceLevelFileConfig{
|
||||
MaxSize: levelCfg.MaxSize,
|
||||
MaxBackups: levelCfg.MaxBackups,
|
||||
MaxAge: levelCfg.MaxAge,
|
||||
Compress: levelCfg.Compress,
|
||||
for k, v := range cfg.Haiyuapi.Logging.LevelConfigs {
|
||||
loggingConfig.LevelConfigs[k] = external_logger.ExternalServiceLevelFileConfig{
|
||||
MaxSize: v.MaxSize,
|
||||
MaxBackups: v.MaxBackups,
|
||||
MaxAge: v.MaxAge,
|
||||
Compress: v.Compress,
|
||||
}
|
||||
}
|
||||
|
||||
logger, err := external_logger.NewExternalServiceLogger(loggingConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
var logger *external_logger.ExternalServiceLogger
|
||||
var err error
|
||||
if loggingConfig.Enabled {
|
||||
logger, err = external_logger.NewExternalServiceLogger(loggingConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
timeout := cfg.Haiyuapi.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = defaultRequestTimeout
|
||||
timeout := defaultRequestTimeout
|
||||
if cfg.Haiyuapi.Timeout > 0 {
|
||||
timeout = cfg.Haiyuapi.Timeout
|
||||
}
|
||||
|
||||
return NewHaiyuapiService(
|
||||
cfg.Haiyuapi.BaseURL,
|
||||
cfg.Haiyuapi.AccessID,
|
||||
cfg.Haiyuapi.SecretKey,
|
||||
timeout,
|
||||
logger,
|
||||
), nil
|
||||
}
|
||||
|
||||
// NewHaiyuapiServiceWithLogging 使用自定义日志配置创建海宇API服务
|
||||
func NewHaiyuapiServiceWithLogging(baseURL, accessID, secretKey string, timeout time.Duration, loggingConfig external_logger.ExternalServiceLoggingConfig) (*HaiyuapiService, error) {
|
||||
loggingConfig.ServiceName = "haiyuapi"
|
||||
|
||||
logger, err := external_logger.NewExternalServiceLogger(loggingConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
serviceCfg := HaiyuapiConfig{
|
||||
BaseURL: cfg.Haiyuapi.BaseURL,
|
||||
AccessID: cfg.Haiyuapi.AccessID,
|
||||
SecretKey: cfg.Haiyuapi.SecretKey,
|
||||
Timeout: timeout,
|
||||
}
|
||||
|
||||
return NewHaiyuapiService(baseURL, accessID, secretKey, timeout, logger), nil
|
||||
}
|
||||
|
||||
// NewHaiyuapiServiceSimple 创建无日志的海宇API服务
|
||||
func NewHaiyuapiServiceSimple(baseURL, accessID, secretKey string, timeout time.Duration) *HaiyuapiService {
|
||||
return NewHaiyuapiService(baseURL, accessID, secretKey, timeout, nil)
|
||||
return NewHaiyuapiService(serviceCfg, logger), nil
|
||||
}
|
||||
|
||||
@@ -16,65 +16,93 @@ import (
|
||||
"tyapi-server/internal/shared/external_logger"
|
||||
)
|
||||
|
||||
const defaultRequestTimeout = 60 * time.Second
|
||||
const (
|
||||
defaultRequestTimeout = 60 * time.Second
|
||||
maxLogParamValueLen = 300
|
||||
maxLogResponseBodyLen = 500
|
||||
)
|
||||
|
||||
// serviceConfig 海宇API服务运行时配置(Access Key 为 16 进制 AES-128 密钥)
|
||||
type serviceConfig struct {
|
||||
// HaiyuapiConfig 海宇 API 服务配置
|
||||
type HaiyuapiConfig struct {
|
||||
BaseURL string
|
||||
AccessID string
|
||||
SecretKey string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// HaiyuapiService 海宇API上游服务客户端
|
||||
// HaiyuapiService 海宇平台中转服务
|
||||
type HaiyuapiService struct {
|
||||
config serviceConfig
|
||||
config HaiyuapiConfig
|
||||
logger *external_logger.ExternalServiceLogger
|
||||
}
|
||||
|
||||
// NewHaiyuapiService 创建海宇API服务实例
|
||||
func NewHaiyuapiService(baseURL, accessID, secretKey string, timeout time.Duration, logger *external_logger.ExternalServiceLogger) *HaiyuapiService {
|
||||
if timeout <= 0 {
|
||||
timeout = defaultRequestTimeout
|
||||
// NewHaiyuapiService 创建海宇 API 服务实例
|
||||
func NewHaiyuapiService(cfg HaiyuapiConfig, logger *external_logger.ExternalServiceLogger) *HaiyuapiService {
|
||||
if cfg.Timeout == 0 {
|
||||
cfg.Timeout = defaultRequestTimeout
|
||||
}
|
||||
return &HaiyuapiService{
|
||||
config: serviceConfig{
|
||||
BaseURL: strings.TrimRight(baseURL, "/"),
|
||||
AccessID: accessID,
|
||||
SecretKey: secretKey,
|
||||
Timeout: timeout,
|
||||
},
|
||||
config: cfg,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CallAPI 调用海宇API:apiPath 如 /api/v1/FLXGHB4F,自动拼接 base_url 与 ?t=13位毫秒时间戳,返回解密后的明文 JSON
|
||||
func (s *HaiyuapiService) CallAPI(ctx context.Context, apiPath string, params map[string]interface{}) ([]byte, error) {
|
||||
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) {
|
||||
startTime := time.Now()
|
||||
hash := md5.Sum([]byte(fmt.Sprintf("%d_%s", time.Now().UnixNano(), s.config.SecretKey)))
|
||||
requestID := fmt.Sprintf("haiyuapi_%x", hash[:8])
|
||||
requestID := s.generateRequestID()
|
||||
|
||||
var transactionID string
|
||||
if id, ok := ctx.Value("transaction_id").(string); ok {
|
||||
transactionID = id
|
||||
}
|
||||
|
||||
path := apiPath
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
path = "/" + path
|
||||
}
|
||||
baseURL := strings.TrimSuffix(s.config.BaseURL, "/")
|
||||
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
|
||||
reqURL := s.config.BaseURL + path + "?t=" + timestamp
|
||||
reqURL := fmt.Sprintf("%s/api/v1/%s?t=%s", baseURL, productCode, timestamp)
|
||||
|
||||
if s.logger != nil {
|
||||
s.logger.LogRequest(requestID, transactionID, apiPath, reqURL)
|
||||
s.logger.LogRequest(requestID, transactionID, productCode, reqURL)
|
||||
}
|
||||
|
||||
encryptedData, err := EncryptParams(params, s.config.SecretKey)
|
||||
if err != nil {
|
||||
err = errors.Join(ErrSystem, fmt.Errorf("请求加密失败: %w", err))
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, apiPath, err, params)
|
||||
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{"request_params": requestParamsForLog(params)})
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
@@ -83,83 +111,137 @@ func (s *HaiyuapiService) CallAPI(ctx context.Context, apiPath string, params ma
|
||||
if err != nil {
|
||||
err = errors.Join(ErrSystem, err)
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, apiPath, err, params)
|
||||
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{"request_params": requestParamsForLog(params)})
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewBuffer(bodyBytes))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(bodyBytes))
|
||||
if err != nil {
|
||||
err = errors.Join(ErrSystem, err)
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, apiPath, err, params)
|
||||
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{"request_params": requestParamsForLog(params)})
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set(HeaderContentType, ContentTypeJSON)
|
||||
req.Header.Set(HeaderAccessID, s.config.AccessID)
|
||||
|
||||
resp, err := (&http.Client{Timeout: s.config.Timeout}).Do(req)
|
||||
client := &http.Client{Timeout: s.config.Timeout}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
err = wrapHTTPError(err)
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, apiPath, err, params)
|
||||
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{"request_params": requestParamsForLog(params)})
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
duration := time.Since(startTime)
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
err = errors.Join(ErrSystem, err)
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, apiPath, err, params)
|
||||
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{"request_params": requestParamsForLog(params)})
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
duration := time.Since(startTime)
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
err = errors.Join(ErrDatasource, fmt.Errorf("HTTP状态码 %d", resp.StatusCode))
|
||||
err = errors.Join(ErrDatasource, fmt.Errorf("HTTP %d", resp.StatusCode))
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, apiPath, err, params)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var apiResp APIResponse
|
||||
if err := json.Unmarshal(respBody, &apiResp); err != nil {
|
||||
err = errors.Join(ErrSystem, fmt.Errorf("响应解析失败: %w", err))
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, apiPath, err, params)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if apiResp.Code != CodeSuccess {
|
||||
apiErr := NewHaiyuapiAPIError(apiResp.Code, apiResp.Message)
|
||||
err = errors.Join(GetErrByCode(apiResp.Code), apiErr)
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, apiPath, apiErr, params)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
plainResp, err := DecryptData(apiResp.Data, s.config.SecretKey)
|
||||
if err != nil {
|
||||
err = errors.Join(ErrSystem, fmt.Errorf("响应解密失败: %w", err))
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, apiPath, err, params)
|
||||
s.logger.LogError(requestID, transactionID, productCode, err, map[string]interface{}{
|
||||
"request_params": requestParamsForLog(params),
|
||||
"response_body": truncateForLog(string(raw), maxLogResponseBodyLen),
|
||||
})
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if s.logger != nil {
|
||||
s.logger.LogResponse(requestID, transactionID, apiPath, resp.StatusCode, duration)
|
||||
s.logger.LogResponse(requestID, transactionID, productCode, resp.StatusCode, duration)
|
||||
}
|
||||
|
||||
return plainResp, nil
|
||||
var outer APIResponse
|
||||
if err := json.Unmarshal(raw, &outer); err != nil {
|
||||
parseErr := errors.Join(ErrSystem, fmt.Errorf("响应解析失败: %w", err))
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, productCode, parseErr, map[string]interface{}{
|
||||
"request_params": requestParamsForLog(params),
|
||||
"response_body": truncateForLog(string(raw), maxLogResponseBodyLen),
|
||||
})
|
||||
}
|
||||
return nil, parseErr
|
||||
}
|
||||
|
||||
if outer.Code != CodeSuccess {
|
||||
mappedErr := mapBusinessError(outer.Code, outer.Message)
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, productCode, mappedErr, map[string]interface{}{
|
||||
"request_params": requestParamsForLog(params),
|
||||
"response_body": truncateForLog(string(raw), maxLogResponseBodyLen),
|
||||
"api_code": outer.Code,
|
||||
})
|
||||
}
|
||||
if errors.Is(mappedErr, ErrNotFound) {
|
||||
return nil, mappedErr
|
||||
}
|
||||
return nil, mappedErr
|
||||
}
|
||||
|
||||
plain, err := DecryptData(outer.Data, s.config.SecretKey)
|
||||
if err != nil {
|
||||
decErr := errors.Join(ErrSystem, fmt.Errorf("解密响应失败: %w", err))
|
||||
if s.logger != nil {
|
||||
s.logger.LogError(requestID, transactionID, productCode, decErr, map[string]interface{}{
|
||||
"request_params": requestParamsForLog(params),
|
||||
"response_body": truncateForLog(string(raw), maxLogResponseBodyLen),
|
||||
})
|
||||
}
|
||||
return nil, decErr
|
||||
}
|
||||
|
||||
if len(plain) == 0 {
|
||||
return []byte("{}"), nil
|
||||
}
|
||||
if !json.Valid(plain) {
|
||||
return plain, nil
|
||||
}
|
||||
return plain, nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
func wrapHTTPError(err error) error {
|
||||
@@ -169,10 +251,9 @@ func wrapHTTPError(err error) error {
|
||||
if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
|
||||
return errors.Join(ErrDatasource, err)
|
||||
}
|
||||
switch err.Error() {
|
||||
case "context deadline exceeded", "timeout", "Client.Timeout exceeded", "net/http: request canceled":
|
||||
es := err.Error()
|
||||
if strings.Contains(es, "deadline exceeded") || strings.Contains(es, "timeout") || strings.Contains(es, "canceled") {
|
||||
return errors.Join(ErrDatasource, err)
|
||||
default:
|
||||
return errors.Join(ErrSystem, err)
|
||||
}
|
||||
return errors.Join(ErrSystem, err)
|
||||
}
|
||||
|
||||
21
internal/infrastructure/external/haiyuapi/haiyuapi_service_test.go
vendored
Normal file
21
internal/infrastructure/external/haiyuapi/haiyuapi_service_test.go
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
package haiyuapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMapBusinessError(t *testing.T) {
|
||||
if err := mapBusinessError(CodeSuccess, ""); err != nil {
|
||||
t.Fatalf("code 0 should be nil, got %v", err)
|
||||
}
|
||||
if !errors.Is(mapBusinessError(CodeQueryEmpty, "查无"), ErrNotFound) {
|
||||
t.Fatal("expected ErrNotFound for 1000")
|
||||
}
|
||||
if !errors.Is(mapBusinessError(CodeBusiness, "业务失败"), ErrDatasource) {
|
||||
t.Fatal("expected ErrDatasource for 2001")
|
||||
}
|
||||
if !errors.Is(mapBusinessError(CodeRequestParam, "参数错误"), ErrSystem) {
|
||||
t.Fatal("expected ErrSystem for 1003")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user