File size: 834 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package apikey
import (
"context"
"sync"
"time"
"github.com/golang/groupcache/lru"
"github.com/google/uuid"
)
type lastUsedCache struct {
lru *lru.Cache
mx sync.Mutex
updateFunc func(ctx context.Context, id uuid.UUID, ua, ip string) error
}
func newLastUsedCache(max int, updateFunc func(ctx context.Context, id uuid.UUID, ua, ip string) error) *lastUsedCache {
return &lastUsedCache{
lru: lru.New(max),
updateFunc: updateFunc,
}
}
func (c *lastUsedCache) RecordUsage(ctx context.Context, id uuid.UUID, ua, ip string) error {
c.mx.Lock()
defer c.mx.Unlock()
// check if we've seen this key recently, and if it's been less than a minute
if t, ok := c.lru.Get(id); ok && time.Since(t.(time.Time)) < time.Minute {
return nil
}
c.lru.Add(id, time.Now())
return c.updateFunc(ctx, id, ua, ip)
}
|