- 全局替换 ApiKey → APIKey(类型、字段、方法、变量) - 修复所有 initialism 命名(API, SMTP, HTML, URL 等) - 添加所有缺失的包注释 - 修复导出符号的注释格式 主要修改: - ApiKey → APIKey(所有出现的地方) - ApiKeyID → APIKeyID - ApiKeyIDs → APIKeyIDs - TestSmtpConnection → TestSMTPConnection - HtmlURL → HTMLURL - 添加 20+ 个包注释 - 修复 10+ 个导出符号注释格式 验证结果: - ✓ golangci-lint: 0 issues - ✓ 单元测试: 通过 - ✓ 集成测试: 通过
61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/service"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
const (
|
|
apiKeyRateLimitKeyPrefix = "apikey:ratelimit:"
|
|
apiKeyRateLimitDuration = 24 * time.Hour
|
|
)
|
|
|
|
// apiKeyRateLimitKey generates the Redis key for API key creation rate limiting.
|
|
func apiKeyRateLimitKey(userID int64) string {
|
|
return fmt.Sprintf("%s%d", apiKeyRateLimitKeyPrefix, userID)
|
|
}
|
|
|
|
type apiKeyCache struct {
|
|
rdb *redis.Client
|
|
}
|
|
|
|
func NewAPIKeyCache(rdb *redis.Client) service.APIKeyCache {
|
|
return &apiKeyCache{rdb: rdb}
|
|
}
|
|
|
|
func (c *apiKeyCache) GetCreateAttemptCount(ctx context.Context, userID int64) (int, error) {
|
|
key := apiKeyRateLimitKey(userID)
|
|
count, err := c.rdb.Get(ctx, key).Int()
|
|
if errors.Is(err, redis.Nil) {
|
|
return 0, nil
|
|
}
|
|
return count, err
|
|
}
|
|
|
|
func (c *apiKeyCache) IncrementCreateAttemptCount(ctx context.Context, userID int64) error {
|
|
key := apiKeyRateLimitKey(userID)
|
|
pipe := c.rdb.Pipeline()
|
|
pipe.Incr(ctx, key)
|
|
pipe.Expire(ctx, key, apiKeyRateLimitDuration)
|
|
_, err := pipe.Exec(ctx)
|
|
return err
|
|
}
|
|
|
|
func (c *apiKeyCache) DeleteCreateAttemptCount(ctx context.Context, userID int64) error {
|
|
key := apiKeyRateLimitKey(userID)
|
|
return c.rdb.Del(ctx, key).Err()
|
|
}
|
|
|
|
func (c *apiKeyCache) IncrementDailyUsage(ctx context.Context, apiKey string) error {
|
|
return c.rdb.Incr(ctx, apiKey).Err()
|
|
}
|
|
|
|
func (c *apiKeyCache) SetDailyUsageExpiry(ctx context.Context, apiKey string, ttl time.Duration) error {
|
|
return c.rdb.Expire(ctx, apiKey, ttl).Err()
|
|
}
|