go-waku/cmd/waku/server/rest/runner.go

49 lines
938 B
Go
Raw Normal View History

package rest
import (
"context"
"github.com/waku-org/go-waku/waku/v2/protocol"
2023-05-05 09:49:15 +00:00
"github.com/waku-org/go-waku/waku/v2/protocol/relay"
)
type Adder func(msg *protocol.Envelope)
type runnerService struct {
2023-05-05 09:49:15 +00:00
broadcaster relay.Broadcaster
sub *relay.Subscription
cancel context.CancelFunc
adder Adder
}
2023-05-05 09:49:15 +00:00
func newRunnerService(broadcaster relay.Broadcaster, adder Adder) *runnerService {
return &runnerService{
broadcaster: broadcaster,
adder: adder,
}
}
func (r *runnerService) Start(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
r.cancel = cancel
r.sub = r.broadcaster.RegisterForAll(relay.WithBufferSize(relay.DefaultRelaySubscriptionBufferSize))
for {
select {
case <-ctx.Done():
return
2023-05-05 09:49:15 +00:00
case envelope, ok := <-r.sub.Ch:
2023-05-05 12:03:44 +00:00
if ok {
2023-05-05 09:49:15 +00:00
r.adder(envelope)
}
}
}
}
func (r *runnerService) Stop() {
2023-01-06 22:37:57 +00:00
if r.cancel == nil {
return
}
2023-05-05 09:49:15 +00:00
r.sub.Unsubscribe()
r.cancel()
}