diff options
| author | Jeroen Wijenbergh <jeroen.wijenbergh@geant.org> | 2026-02-12 12:34:08 +0100 |
|---|---|---|
| committer | Jeroen Wijenbergh <jeroen.wijenbergh@geant.org> | 2026-02-12 12:59:03 +0100 |
| commit | a30ef6b27e578a4cf0a674b24f5b52b4c1516c63 (patch) | |
| tree | 27c7321cbceac2a487c1ba17151711de3d438a53 /internal/eduvpnapi/cache.go | |
| parent | b00ce8214479c50e137db73c77b0cc1393c5e7d4 (diff) | |
All: Rename packages that sound useless or clash with std
Diffstat (limited to 'internal/eduvpnapi/cache.go')
| -rw-r--r-- | internal/eduvpnapi/cache.go | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/internal/eduvpnapi/cache.go b/internal/eduvpnapi/cache.go new file mode 100644 index 0000000..d3e2b77 --- /dev/null +++ b/internal/eduvpnapi/cache.go @@ -0,0 +1,67 @@ +package eduvpnapi + +import ( + "context" + "net/http" + "sync" + "time" + + "codeberg.org/eduVPN/eduvpn-common/internal/eduvpnapi/endpoints" +) + +// EndpointCache is a struct that caches well-known API endpoints +type EndpointCache struct { + lastUpdate map[string]time.Time + lastEP map[string]*endpoints.Endpoints + mu sync.Mutex +} + +// Get returns a cached or fresh endpoint cache copy +func (ec *EndpointCache) Get(ctx context.Context, wk string, transport http.RoundTripper) (*endpoints.Endpoints, error) { + ec.mu.Lock() + defer ec.mu.Unlock() + + // get the last update time + lu := time.Time{} + if v, ok := ec.lastUpdate[wk]; ok { + lu = v + } + + // if not 10 minutes have passed, return cached copy + if !lu.IsZero() && !time.Now().After(lu.Add(10*time.Minute)) { + v, ok := ec.lastEP[wk] + if ok { + return v, nil + } + } + + // get fresh API endpoints + ep, err := getEndpoints(ctx, wk, transport) + if err != nil { + return nil, err + } + + // update endpoints + ec.lastUpdate[wk] = time.Now() + ec.lastEP[wk] = ep + + return ep, nil +} + +var ( + epCache *EndpointCache + epCacheOnce sync.Once +) + +// GetEndpointCache returns the global singleton endpoint cache +// or creates one if it does not exist +func GetEndpointCache() *EndpointCache { + epCacheOnce.Do(func() { + epCache = &EndpointCache{ + lastUpdate: make(map[string]time.Time), + lastEP: make(map[string]*endpoints.Endpoints), + } + }) + + return epCache +} |
