Files
schemas/cache/cache.go
T

66 lines
1.7 KiB
Go
Raw Normal View History

2022-10-09 15:23:52 +02:00
package cache
import (
"fmt"
2022-10-14 22:41:56 +02:00
"time"
2022-10-09 15:23:52 +02:00
"github.com/apex/log"
"github.com/sparetimecoders/goamqp"
"gitlab.com/unboundsoftware/schemas/domain"
)
const subGraphKey = "%s<->%s"
type Cache struct {
2022-10-14 22:41:56 +02:00
services map[string]map[string]struct{}
subGraphs map[string]string
lastUpdate map[string]string
logger log.Interface
2022-10-09 15:23:52 +02:00
}
2022-10-14 22:41:56 +02:00
func (c *Cache) Services(ref, lastUpdate string) ([]string, string) {
2022-10-09 15:23:52 +02:00
var services []string
2022-10-14 22:41:56 +02:00
if lastUpdate == "" || c.lastUpdate[ref] > lastUpdate {
for k := range c.services[ref] {
services = append(services, k)
}
2022-10-09 15:23:52 +02:00
}
2022-10-14 22:41:56 +02:00
return services, c.lastUpdate[ref]
2022-10-09 15:23:52 +02:00
}
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()
2022-10-14 22:41:56 +02:00
c.lastUpdate[m.Ref] = m.Time.Format(time.RFC3339Nano)
2022-10-09 15:23:52 +02:00
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()
2022-10-14 22:41:56 +02:00
c.lastUpdate[m.Ref] = m.ChangedAt.Format(time.RFC3339Nano)
2022-10-09 15:23:52 +02:00
default:
c.logger.Warnf("unexpected message received: %+v", msg)
}
return nil, nil
}
func New(logger log.Interface) *Cache {
return &Cache{
2022-10-14 22:41:56 +02:00
subGraphs: make(map[string]string),
services: make(map[string]map[string]struct{}),
lastUpdate: make(map[string]string),
logger: logger,
2022-10-09 15:23:52 +02:00
}
}