v0.1
This commit is contained in:
196
internal/domains/api/entities/api_call.go
Normal file
196
internal/domains/api/entities/api_call.go
Normal file
@@ -0,0 +1,196 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/shopspring/decimal"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ApiCallStatus API调用状态
|
||||
const (
|
||||
ApiCallStatusPending = "pending"
|
||||
ApiCallStatusSuccess = "success"
|
||||
ApiCallStatusFailed = "failed"
|
||||
)
|
||||
|
||||
// ApiCall错误类型常量定义,供各领域服务和应用层统一引用。
|
||||
// 使用时可通过 entities.ApiCallErrorInvalidAccess 方式获得,编辑器可自动补全和提示。
|
||||
// 错误类型与业务含义:
|
||||
//
|
||||
// ApiCallErrorInvalidAccess = "invalid_access" // 无效AccessId
|
||||
// ApiCallErrorFrozenAccount = "frozen_account" // 账户冻结
|
||||
// ApiCallErrorInvalidIP = "invalid_ip" // IP无效
|
||||
// ApiCallErrorArrears = "arrears" // 账户欠费
|
||||
// ApiCallErrorNotSubscribed = "not_subscribed" // 未订阅产品
|
||||
// ApiCallErrorProductNotFound = "product_not_found" // 产品不存在
|
||||
// ApiCallErrorProductDisabled = "product_disabled" // 产品已停用
|
||||
// ApiCallErrorSystem = "system_error" // 系统错误
|
||||
// ApiCallErrorDatasource = "datasource_error" // 数据源异常
|
||||
// ApiCallErrorInvalidParam = "invalid_param" // 参数不正确
|
||||
// ApiCallErrorDecryptFail = "decrypt_fail" // 解密失败
|
||||
const (
|
||||
ApiCallErrorInvalidAccess = "invalid_access" // 无效AccessId
|
||||
ApiCallErrorFrozenAccount = "frozen_account" // 账户冻结
|
||||
ApiCallErrorInvalidIP = "invalid_ip" // IP无效
|
||||
ApiCallErrorArrears = "arrears" // 账户欠费
|
||||
ApiCallErrorNotSubscribed = "not_subscribed" // 未订阅产品
|
||||
ApiCallErrorProductNotFound = "product_not_found" // 产品不存在
|
||||
ApiCallErrorProductDisabled = "product_disabled" // 产品已停用
|
||||
ApiCallErrorSystem = "system_error" // 系统错误
|
||||
ApiCallErrorDatasource = "datasource_error" // 数据源异常
|
||||
ApiCallErrorInvalidParam = "invalid_param" // 参数不正确
|
||||
ApiCallErrorDecryptFail = "decrypt_fail" // 解密失败
|
||||
ApiCallErrorQueryEmpty = "query_empty" // 查询为空
|
||||
)
|
||||
|
||||
// ApiCall API调用(聚合根)
|
||||
type ApiCall struct {
|
||||
ID string `gorm:"type:varchar(64);primaryKey" json:"id"`
|
||||
AccessId string `gorm:"type:varchar(64);not null;index" json:"access_id"`
|
||||
UserId *string `gorm:"type:varchar(36);index" json:"user_id,omitempty"`
|
||||
ProductId *string `gorm:"type:varchar(64);index" json:"product_id,omitempty"`
|
||||
TransactionId string `gorm:"type:varchar(64);not null;uniqueIndex" json:"transaction_id"`
|
||||
ClientIp string `gorm:"type:varchar(64);not null;index" json:"client_ip"`
|
||||
RequestParams string `gorm:"type:text" json:"request_params"`
|
||||
ResponseData *string `gorm:"type:text" json:"response_data,omitempty"`
|
||||
Status string `gorm:"type:varchar(20);not null;default:'pending'" json:"status"`
|
||||
StartAt time.Time `gorm:"not null;index" json:"start_at"`
|
||||
EndAt *time.Time `gorm:"index" json:"end_at,omitempty"`
|
||||
Cost *decimal.Decimal `gorm:"default:0" json:"cost,omitempty"`
|
||||
ErrorType *string `gorm:"type:varchar(32)" json:"error_type,omitempty"`
|
||||
ErrorMsg *string `gorm:"type:varchar(256)" json:"error_msg,omitempty"`
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
// NewApiCall 工厂方法
|
||||
func NewApiCall(accessId, requestParams, clientIp string) (*ApiCall, error) {
|
||||
if accessId == "" {
|
||||
return nil, errors.New("AccessId不能为空")
|
||||
}
|
||||
if requestParams == "" {
|
||||
return nil, errors.New("请求参数不能为空")
|
||||
}
|
||||
if clientIp == "" {
|
||||
return nil, errors.New("ClientIp不能为空")
|
||||
}
|
||||
|
||||
return &ApiCall{
|
||||
ID: uuid.New().String(),
|
||||
AccessId: accessId,
|
||||
TransactionId: GenerateTransactionID(),
|
||||
ClientIp: clientIp,
|
||||
RequestParams: requestParams,
|
||||
Status: ApiCallStatusPending,
|
||||
StartAt: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// MarkSuccess 标记为成功
|
||||
func (a *ApiCall) MarkSuccess(responseData string, cost decimal.Decimal) error {
|
||||
// 校验除ErrorMsg和ErrorType外所有字段不能为空
|
||||
if a.ID == "" || a.AccessId == "" || a.TransactionId == "" || a.RequestParams == "" || a.Status == "" || a.StartAt.IsZero() {
|
||||
return errors.New("ApiCall字段不能为空(除ErrorMsg和ErrorType)")
|
||||
}
|
||||
// 可选字段也要有值
|
||||
if a.UserId == nil || a.ProductId == nil || responseData == "" {
|
||||
return errors.New("ApiCall标记成功时UserId、ProductId、ResponseData不能为空")
|
||||
}
|
||||
a.Status = ApiCallStatusSuccess
|
||||
a.ResponseData = &responseData
|
||||
endAt := time.Now()
|
||||
a.EndAt = &endAt
|
||||
a.Cost = &cost
|
||||
a.ErrorType = nil
|
||||
a.ErrorMsg = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkFailed 标记为失败
|
||||
func (a *ApiCall) MarkFailed(errorType, errorMsg string) {
|
||||
a.Status = ApiCallStatusFailed
|
||||
a.ErrorType = &errorType
|
||||
shortMsg := errorMsg
|
||||
if len(shortMsg) > 120 {
|
||||
shortMsg = shortMsg[:120]
|
||||
}
|
||||
a.ErrorMsg = &shortMsg
|
||||
endAt := time.Now()
|
||||
a.EndAt = &endAt
|
||||
}
|
||||
|
||||
// Validate 校验ApiCall聚合根的业务规则
|
||||
func (a *ApiCall) Validate() error {
|
||||
if a.ID == "" {
|
||||
return errors.New("ID不能为空")
|
||||
}
|
||||
if a.AccessId == "" {
|
||||
return errors.New("AccessId不能为空")
|
||||
}
|
||||
if a.TransactionId == "" {
|
||||
return errors.New("TransactionId不能为空")
|
||||
}
|
||||
if a.RequestParams == "" {
|
||||
return errors.New("请求参数不能为空")
|
||||
}
|
||||
if a.Status != ApiCallStatusPending && a.Status != ApiCallStatusSuccess && a.Status != ApiCallStatusFailed {
|
||||
return errors.New("无效的调用状态")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 全局计数器,用于确保TransactionID的唯一性
|
||||
var (
|
||||
transactionCounter int64
|
||||
counterMutex sync.Mutex
|
||||
)
|
||||
|
||||
// GenerateTransactionID 生成16位数的交易单号
|
||||
func GenerateTransactionID() string {
|
||||
// 使用互斥锁确保计数器的线程安全
|
||||
counterMutex.Lock()
|
||||
transactionCounter++
|
||||
currentCounter := transactionCounter
|
||||
counterMutex.Unlock()
|
||||
|
||||
// 获取当前时间戳(微秒精度)
|
||||
timestamp := time.Now().UnixMicro()
|
||||
|
||||
// 组合时间戳和计数器,确保唯一性
|
||||
combined := fmt.Sprintf("%d%06d", timestamp, currentCounter%1000000)
|
||||
|
||||
// 如果长度超出16位,截断;如果不够,填充随机字符
|
||||
if len(combined) >= 16 {
|
||||
return combined[:16]
|
||||
}
|
||||
|
||||
// 如果长度不够,使用随机字节填充
|
||||
if len(combined) < 16 {
|
||||
randomBytes := make([]byte, 8)
|
||||
rand.Read(randomBytes)
|
||||
randomHex := hex.EncodeToString(randomBytes)
|
||||
combined += randomHex[:16-len(combined)]
|
||||
}
|
||||
|
||||
return combined
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (ApiCall) TableName() string {
|
||||
return "api_calls"
|
||||
}
|
||||
|
||||
// BeforeCreate GORM钩子:创建前自动生成UUID
|
||||
func (c *ApiCall) BeforeCreate(tx *gorm.DB) error {
|
||||
if c.ID == "" {
|
||||
c.ID = uuid.New().String()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
193
internal/domains/api/entities/api_user.go
Normal file
193
internal/domains/api/entities/api_user.go
Normal file
@@ -0,0 +1,193 @@
|
||||
package entities
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ApiUserStatus API用户状态
|
||||
const (
|
||||
ApiUserStatusNormal = "normal"
|
||||
ApiUserStatusFrozen = "frozen"
|
||||
)
|
||||
|
||||
// ApiUser API用户(聚合根)
|
||||
type ApiUser struct {
|
||||
ID string `gorm:"primaryKey;type:varchar(64)" json:"id"`
|
||||
UserId string `gorm:"type:varchar(36);not null;uniqueIndex" json:"user_id"`
|
||||
AccessId string `gorm:"type:varchar(64);not null;uniqueIndex" json:"access_id"`
|
||||
SecretKey string `gorm:"type:varchar(128);not null" json:"secret_key"`
|
||||
Status string `gorm:"type:varchar(20);not null;default:'normal'" json:"status"`
|
||||
WhiteList []string `gorm:"type:json;serializer:json;default:'[]'" json:"white_list"` // 支持多个白名单
|
||||
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
// IsWhiteListed 校验IP/域名是否在白名单
|
||||
func (u *ApiUser) IsWhiteListed(target string) bool {
|
||||
for _, w := range u.WhiteList {
|
||||
if w == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsActive 是否可用
|
||||
func (u *ApiUser) IsActive() bool {
|
||||
return u.Status == ApiUserStatusNormal
|
||||
}
|
||||
|
||||
// IsFrozen 是否冻结
|
||||
func (u *ApiUser) IsFrozen() bool {
|
||||
return u.Status == ApiUserStatusFrozen
|
||||
}
|
||||
|
||||
// NewApiUser 工厂方法
|
||||
func NewApiUser(userId string) (*ApiUser, error) {
|
||||
if userId == "" {
|
||||
return nil, errors.New("用户ID不能为空")
|
||||
}
|
||||
accessId, err := GenerateSecretId()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
secretKey, err := GenerateSecretKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ApiUser{
|
||||
ID: uuid.New().String(),
|
||||
UserId: userId,
|
||||
AccessId: accessId,
|
||||
SecretKey: secretKey,
|
||||
Status: ApiUserStatusNormal,
|
||||
WhiteList: []string{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 领域行为
|
||||
func (u *ApiUser) Freeze() {
|
||||
u.Status = ApiUserStatusFrozen
|
||||
}
|
||||
func (u *ApiUser) Unfreeze() {
|
||||
u.Status = ApiUserStatusNormal
|
||||
}
|
||||
func (u *ApiUser) UpdateWhiteList(list []string) {
|
||||
u.WhiteList = list
|
||||
}
|
||||
|
||||
// AddToWhiteList 新增白名单项(防御性校验)
|
||||
func (u *ApiUser) AddToWhiteList(entry string) error {
|
||||
if len(u.WhiteList) >= 10 {
|
||||
return errors.New("白名单最多只能有10个")
|
||||
}
|
||||
if net.ParseIP(entry) == nil {
|
||||
return errors.New("非法IP")
|
||||
}
|
||||
for _, w := range u.WhiteList {
|
||||
if w == entry {
|
||||
return errors.New("白名单已存在")
|
||||
}
|
||||
}
|
||||
u.WhiteList = append(u.WhiteList, entry)
|
||||
return nil
|
||||
}
|
||||
|
||||
// BeforeUpdate GORM钩子:更新前确保WhiteList不为nil
|
||||
func (u *ApiUser) BeforeUpdate(tx *gorm.DB) error {
|
||||
if u.WhiteList == nil {
|
||||
u.WhiteList = []string{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveFromWhiteList 删除白名单项
|
||||
func (u *ApiUser) RemoveFromWhiteList(entry string) error {
|
||||
newList := make([]string, 0, len(u.WhiteList))
|
||||
for _, w := range u.WhiteList {
|
||||
if w != entry {
|
||||
newList = append(newList, w)
|
||||
}
|
||||
}
|
||||
if len(newList) == len(u.WhiteList) {
|
||||
return errors.New("白名单不存在")
|
||||
}
|
||||
u.WhiteList = newList
|
||||
return nil
|
||||
}
|
||||
|
||||
// Validate 校验ApiUser聚合根的业务规则
|
||||
func (u *ApiUser) Validate() error {
|
||||
if u.UserId == "" {
|
||||
return errors.New("用户ID不能为空")
|
||||
}
|
||||
if u.AccessId == "" {
|
||||
return errors.New("AccessId不能为空")
|
||||
}
|
||||
if u.SecretKey == "" {
|
||||
return errors.New("SecretKey不能为空")
|
||||
}
|
||||
switch u.Status {
|
||||
case ApiUserStatusNormal, ApiUserStatusFrozen:
|
||||
// ok
|
||||
default:
|
||||
return errors.New("无效的用户状态")
|
||||
}
|
||||
if len(u.WhiteList) > 10 {
|
||||
return errors.New("白名单最多只能有10个")
|
||||
}
|
||||
for _, ip := range u.WhiteList {
|
||||
if net.ParseIP(ip) == nil {
|
||||
return errors.New("白名单项必须为合法IP地址: " + ip)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 生成AES-128密钥的函数,符合市面规范
|
||||
func GenerateSecretKey() (string, error) {
|
||||
key := make([]byte, 16) // 16字节密钥
|
||||
_, err := io.ReadFull(rand.Reader, key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
func GenerateSecretId() (string, error) {
|
||||
// 创建一个字节数组,用于存储随机数据
|
||||
bytes := make([]byte, 8) // 因为每个字节表示两个16进制字符
|
||||
|
||||
// 读取随机字节到数组中
|
||||
_, err := rand.Read(bytes)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 将字节数组转换为16进制字符串
|
||||
return hex.EncodeToString(bytes), nil
|
||||
}
|
||||
|
||||
// TableName 指定数据库表名
|
||||
func (ApiUser) TableName() string {
|
||||
return "api_users"
|
||||
}
|
||||
|
||||
// BeforeCreate GORM钩子:创建前自动生成UUID并确保WhiteList不为nil
|
||||
func (c *ApiUser) BeforeCreate(tx *gorm.DB) error {
|
||||
if c.ID == "" {
|
||||
c.ID = uuid.New().String()
|
||||
}
|
||||
if c.WhiteList == nil {
|
||||
c.WhiteList = []string{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user