// Copyright © 2023 Roberto Hidalgo // SPDX-License-Identifier: Apache-2.0 package consul import ( "encoding/json" "git.rob.mx/nidito/chinampa/pkg/logger" "git.rob.mx/nidito/event-gateway/internal/config" "git.rob.mx/nidito/event-gateway/internal/source/types" "github.com/hashicorp/consul/api" ) var log = logger.Sub("event-gateway.source.http") type Client interface { List(name string, q *api.QueryOptions) ([]*api.UserEvent, *api.QueryMeta, error) } type Source struct { watches map[string]*watch Client Client } var _ config.Source = &Source{} func New(client Client) *Source { s := &Source{Client: client} s.Initialize() return s } func (src *Source) Kind() types.Kind { return types.Consul } func (src *Source) Initialize() { if src.watches == nil { src.watches = map[string]*watch{} } } func (src *Source) Register(l *config.Listener) error { listener := &watch{Name: l.ID, Event: l.Event} if err := json.Unmarshal(l.Source.Config, &listener); err != nil { return err } if l, ok := src.watches[listener.Name]; ok { listener.lastIndex = l.lastIndex listener.cancel = l.cancel } src.watches[listener.Name] = listener listener.Watch(src.Client) return nil } func (src *Source) Deregister(id string) { if watch, ok := src.watches[id]; ok { log.Debugf("Clearing watch for consul:%s", watch.Name) watch.cancel() delete(src.watches, id) } }