cache.go54 lines, 1.4 KB
| 1 | package notification |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "sync" |
| 6 | "time" |
| 7 | |
| 8 | "github.com/google/uuid" |
| 9 | ) |
| 10 | |
| 11 | // maxCached caps the cache's size: once it's full, it starts over. |
| 12 | const maxCached = 10_000 |
| 13 | |
| 14 | // CachedUsers remembers addresses for a while. A transfer sends two emails, |
| 15 | // and an active user gets many, so most lookups never reach auth. A changed |
| 16 | // address is picked up within ttl. |
| 17 | type CachedUsers struct { |
| 18 | users Users |
| 19 | ttl time.Duration |
| 20 | |
| 21 | mu sync.Mutex // guards entries: Email is called from many goroutines |
| 22 | entries map[uuid.UUID]cachedEmail |
| 23 | } |
| 24 | |
| 25 | type cachedEmail struct { |
| 26 | email string |
| 27 | expires time.Time |
| 28 | } |
| 29 | |
| 30 | // NewCachedUsers returns users, with every address cached for ttl. |
| 31 | func NewCachedUsers(users Users, ttl time.Duration) *CachedUsers { |
| 32 | return &CachedUsers{users: users, ttl: ttl, entries: make(map[uuid.UUID]cachedEmail)} |
| 33 | } |
| 34 | |
| 35 | func (c *CachedUsers) Email(ctx context.Context, id uuid.UUID) (string, error) { |
| 36 | c.mu.Lock() |
| 37 | e, ok := c.entries[id] |
| 38 | c.mu.Unlock() |
| 39 | if ok && time.Now().Before(e.expires) { |
| 40 | return e.email, nil |
| 41 | } |
| 42 | // Not while holding the lock: one slow call to auth would stall them all. |
| 43 | email, err := c.users.Email(ctx, id) |
| 44 | if err != nil { |
| 45 | return "", err // never cached: the next try asks again |
| 46 | } |
| 47 | c.mu.Lock() |
| 48 | defer c.mu.Unlock() |
| 49 | if len(c.entries) >= maxCached { |
| 50 | clear(c.entries) |
| 51 | } |
| 52 | c.entries[id] = cachedEmail{email: email, expires: time.Now().Add(c.ttl)} |
| 53 | return email, nil |
| 54 | } |