Skip to content

FEAT: Add ZoneCache primitive #3365

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 15, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions pkg/zoneCache/zoneCache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package zoneCache

import (
"errors"
"sync"
)

func New[Zone any](fetchAll func() (map[string]Zone, error)) ZoneCache[Zone] {
return ZoneCache[Zone]{fetchAll: fetchAll}
}

var ErrZoneNotFound = errors.New("zone not found")

type ZoneCache[Zone any] struct {
mu sync.Mutex
cached bool
cache map[string]Zone
fetchAll func() (map[string]Zone, error)
}

func (c *ZoneCache[Zone]) ensureCached() error {
if c.cached {
return nil
}
zones, err := c.fetchAll()
if err != nil {
return err
}
if c.cache == nil {
c.cache = make(map[string]Zone, len(zones))
}
for name, z := range zones {
c.cache[name] = z
}
return nil
}

func (c *ZoneCache[Zone]) HasZone(name string) (bool, error) {
c.mu.Lock()
defer c.mu.Unlock()

if err := c.ensureCached(); err != nil {
return false, err
}
_, ok := c.cache[name]
return ok, nil
}

func (c *ZoneCache[Zone]) GetZone(name string) (Zone, error) {
c.mu.Lock()
defer c.mu.Unlock()

if err := c.ensureCached(); err != nil {
var z Zone
return z, err
}
z, ok := c.cache[name]
if !ok {
return z, ErrZoneNotFound
}
return z, nil
}

func (c *ZoneCache[Zone]) GetZoneNames() ([]string, error) {
c.mu.Lock()
defer c.mu.Unlock()

if err := c.ensureCached(); err != nil {
return nil, err
}
names := make([]string, 0, len(c.cache))
for name := range c.cache {
names = append(names, name)
}
return names, nil
}

func (c *ZoneCache[Zone]) SetZone(name string, z Zone) {
c.mu.Lock()
defer c.mu.Unlock()

if c.cache == nil {
c.cache = make(map[string]Zone, 1)
}
c.cache[name] = z
}