Write on the margins of the internet. Powered by the AT Protocol.
margin.at
extension
web
atproto
comments
1package api
2
3import (
4 "sync"
5 "time"
6)
7
8type ProfileCache interface {
9 Get(did string) (Author, bool)
10 Set(did string, profile Author)
11}
12type InMemoryCache struct {
13 cache sync.Map
14 ttl time.Duration
15}
16
17type cachedProfile struct {
18 Author Author
19 ExpiresAt time.Time
20}
21
22func NewInMemoryCache(ttl time.Duration) *InMemoryCache {
23 return &InMemoryCache{
24 ttl: ttl,
25 }
26}
27
28func (c *InMemoryCache) Get(did string) (Author, bool) {
29 val, ok := c.cache.Load(did)
30 if !ok {
31 return Author{}, false
32 }
33
34 entry := val.(cachedProfile)
35 if time.Now().After(entry.ExpiresAt) {
36 c.cache.Delete(did)
37 return Author{}, false
38 }
39
40 return entry.Author, true
41}
42
43func (c *InMemoryCache) Set(did string, profile Author) {
44 c.cache.Store(did, cachedProfile{
45 Author: profile,
46 ExpiresAt: time.Now().Add(c.ttl),
47 })
48}