Files
schemas/cache/cache.go
T

66 lines
1.7 KiB
Go

package cache
import (
"fmt"
"time"
"github.com/apex/log"
"github.com/sparetimecoders/goamqp"
"gitlab.com/unboundsoftware/schemas/domain"
)
const subGraphKey = "%s<->%s"
type Cache struct {
services map[string]map[string]struct{}
subGraphs map[string]string
lastUpdate map[string]string
logger log.Interface
}
func (c *Cache) Services(ref, lastUpdate string) ([]string, string) {
var services []string
if lastUpdate == "" || c.lastUpdate[ref] > lastUpdate {
for k := range c.services[ref] {
services = append(services, k)
}
}
return services, c.lastUpdate[ref]
}
func (c *Cache) SubGraphId(ref, service string) string {
return c.subGraphs[fmt.Sprintf(subGraphKey, ref, service)]
}
func (c *Cache) Update(msg any, _ goamqp.Headers) (any, error) {
switch m := msg.(type) {
case *domain.SubGraphUpdated:
if _, exists := c.services[m.Ref]; !exists {
c.services[m.Ref] = make(map[string]struct{})
}
c.services[m.Ref][m.ID.String()] = struct{}{}
c.subGraphs[fmt.Sprintf(subGraphKey, m.Ref, m.Service)] = m.ID.String()
c.lastUpdate[m.Ref] = m.Time.Format(time.RFC3339Nano)
case *domain.SubGraph:
if _, exists := c.services[m.Ref]; !exists {
c.services[m.Ref] = make(map[string]struct{})
}
c.services[m.Ref][m.ID.String()] = struct{}{}
c.subGraphs[fmt.Sprintf(subGraphKey, m.Ref, m.Service)] = m.ID.String()
c.lastUpdate[m.Ref] = m.ChangedAt.Format(time.RFC3339Nano)
default:
c.logger.Warnf("unexpected message received: %+v", msg)
}
return nil, nil
}
func New(logger log.Interface) *Cache {
return &Cache{
subGraphs: make(map[string]string),
services: make(map[string]map[string]struct{}),
lastUpdate: make(map[string]string),
logger: logger,
}
}