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
@@ -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)
}
}