feat(api-keys): implement throttled last_used_at updates for API key authentication

Enhance the tenant API key service by introducing asynchronous throttling for the last_used_at updates during API key authentication. This change reduces database write frequency under high request rates, improving performance. Additionally, update tests to validate the throttling behavior, ensuring that last_used_at is only updated once per key within the defined interval. This implementation aligns with the goal of optimizing API key management and maintaining system efficiency.
This commit is contained in:
wizardchen
2026-07-06 19:38:16 +08:00
committed by lyingbug
parent 97c36f634a
commit b5cc7d2a28
4 changed files with 175 additions and 43 deletions
+30 -2
View File
@@ -8,15 +8,23 @@ import (
"encoding/hex"
"errors"
"strings"
"sync"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// apiKeyLastUsedMinInterval bounds how often we persist last_used_at per key.
// The UI only needs minute-level freshness; throttling avoids a DB write on
// every authenticated request under high QPS.
const apiKeyLastUsedMinInterval = time.Minute
type tenantAPIKeyService struct {
repo interfaces.TenantAPIKeyRepository
repo interfaces.TenantAPIKeyRepository
lastUsedTouch sync.Map // key ID (uint64) -> time.Time of last persisted touch
}
func NewTenantAPIKeyService(repo interfaces.TenantAPIKeyRepository) interfaces.TenantAPIKeyService {
@@ -70,10 +78,30 @@ func (s *tenantAPIKeyService) AuthenticateAPIKey(ctx context.Context, token stri
if key.ExpiresAt != nil && time.Now().After(*key.ExpiresAt) {
return nil, apprepo.ErrTenantAPIKeyNotFound
}
_ = s.repo.UpdateAPIKeyLastUsed(ctx, key.ID, time.Now())
s.touchAPIKeyLastUsedAsync(key.ID)
return key, nil
}
// touchAPIKeyLastUsedAsync persists last_used_at at most once per key per
// apiKeyLastUsedMinInterval. The write runs in a detached goroutine so auth
// latency is not tied to an UPDATE on the hot path.
func (s *tenantAPIKeyService) touchAPIKeyLastUsedAsync(keyID uint64) {
now := time.Now()
if v, ok := s.lastUsedTouch.Load(keyID); ok {
if now.Sub(v.(time.Time)) < apiKeyLastUsedMinInterval {
return
}
}
s.lastUsedTouch.Store(keyID, now)
go func(id uint64, at time.Time) {
if err := s.repo.UpdateAPIKeyLastUsed(context.Background(), id, at); err != nil {
logger.Warnf(context.Background(),
"failed to update tenant api key last_used_at (id=%d): %v", id, err)
s.lastUsedTouch.Delete(id)
}
}(keyID, now)
}
func (s *tenantAPIKeyService) ListAPIKeys(ctx context.Context, tenantID uint64) ([]*types.TenantAPIKey, error) {
return s.repo.ListAPIKeys(ctx, tenantID)
}
@@ -13,8 +13,9 @@ import (
)
type fakeTenantAPIKeyRepo struct {
byHash map[string]*types.TenantAPIKey
nextID uint64
byHash map[string]*types.TenantAPIKey
nextID uint64
lastUsedUpdateCount int
}
func TestTenantAPIKeyServiceCreateAPIKeyUsesSKPrefix(t *testing.T) {
@@ -118,6 +119,7 @@ func (r *fakeTenantAPIKeyRepo) ListKeysWithPlaceholderHash(_ context.Context) ([
}
func (r *fakeTenantAPIKeyRepo) UpdateAPIKeyLastUsed(_ context.Context, id uint64, at time.Time) error {
r.lastUsedUpdateCount++
for _, key := range r.byHash {
if key.ID == id && key.RevokedAt == nil {
key.LastUsedAt = &at
@@ -178,3 +180,32 @@ func TestTenantAPIKeyServiceRevokeAPIKey(t *testing.T) {
t.Fatal("revoked key should not authenticate")
}
}
func TestTenantAPIKeyServiceAuthenticateThrottlesLastUsedUpdates(t *testing.T) {
ctx := context.Background()
repo := newFakeTenantAPIKeyRepo()
svc := NewTenantAPIKeyService(repo)
created, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
TenantID: 42,
Name: "integration",
Role: types.TenantRoleViewer,
})
if err != nil {
t.Fatalf("CreateAPIKey returned error: %v", err)
}
for i := 0; i < 5; i++ {
if _, err := svc.AuthenticateAPIKey(ctx, created.Token); err != nil {
t.Fatalf("AuthenticateAPIKey #%d returned error: %v", i+1, err)
}
}
deadline := time.Now().Add(500 * time.Millisecond)
for repo.lastUsedUpdateCount == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if repo.lastUsedUpdateCount != 1 {
t.Fatalf("last_used update count = %d, want 1 (throttled async write)", repo.lastUsedUpdateCount)
}
}