forked from tangled.org/core
Monorepo for Tangled — https://tangled.org

knotclient: improve api with NewConsumerConfig and AddEventSource

Signed-off-by: Anirudh Oppiliappan <anirudh@tangled.sh>

anirudh.fi 92de0157 d95215cc

verified
Changed files
+17 -7
knotclient
+17 -7
knotclient/events.go
···
"github.com/gorilla/websocket"
)
-
type ProcessFunc func(source EventSource, message Message) error
type Message struct {
Rkey string
···
CursorStore CursorStore
}
type EventSource struct {
Knot string
}
···
}
type EventConsumer struct {
-
cfg ConsumerConfig
wg sync.WaitGroup
dialer *websocket.Dialer
connMap sync.Map
···
logger *slog.Logger
randSource *rand.Rand
-
// rw lock over edits to consumer config
-
mu sync.RWMutex
}
type CursorStore interface {
···
}
func (c *EventConsumer) AddSource(ctx context.Context, s EventSource) {
-
c.mu.Lock()
c.cfg.Sources[s] = struct{}{}
c.wg.Add(1)
go c.startConnectionLoop(ctx, s)
-
c.mu.Unlock()
}
func (c *EventConsumer) worker(ctx context.Context) {
···
// update cursor
c.cfg.CursorStore.Set(j.source.Knot, time.Now().Unix())
-
if err := c.cfg.ProcessFunc(j.source, msg); err != nil {
c.logger.Error("error processing message", "source", j.source, "err", err)
}
}
···
"github.com/gorilla/websocket"
)
+
type ProcessFunc func(ctx context.Context, source EventSource, message Message) error
type Message struct {
Rkey string
···
CursorStore CursorStore
}
+
func NewConsumerConfig() *ConsumerConfig {
+
return &ConsumerConfig{
+
Sources: make(map[EventSource]struct{}),
+
}
+
}
+
+
func (cc *ConsumerConfig) AddEventSource(es EventSource) {
+
cc.Sources[es] = struct{}{}
+
}
+
type EventSource struct {
Knot string
}
···
}
type EventConsumer struct {
wg sync.WaitGroup
dialer *websocket.Dialer
connMap sync.Map
···
logger *slog.Logger
randSource *rand.Rand
+
// rw lock over edits to ConsumerConfig
+
cfgMu sync.RWMutex
+
cfg ConsumerConfig
}
type CursorStore interface {
···
}
func (c *EventConsumer) AddSource(ctx context.Context, s EventSource) {
+
c.cfgMu.Lock()
c.cfg.Sources[s] = struct{}{}
c.wg.Add(1)
go c.startConnectionLoop(ctx, s)
+
c.cfgMu.Unlock()
}
func (c *EventConsumer) worker(ctx context.Context) {
···
// update cursor
c.cfg.CursorStore.Set(j.source.Knot, time.Now().Unix())
+
if err := c.cfg.ProcessFunc(ctx, j.source, msg); err != nil {
c.logger.Error("error processing message", "source", j.source, "err", err)
}
}