2022-07-24 20:51:42 +00:00
|
|
|
package rest
|
|
|
|
|
|
|
|
import (
|
2022-12-10 16:21:22 +00:00
|
|
|
"context"
|
|
|
|
|
2022-11-09 19:53:01 +00:00
|
|
|
"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"
|
2022-07-24 20:51:42 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Adder func(msg *protocol.Envelope)
|
|
|
|
|
|
|
|
type runnerService struct {
|
2023-05-05 09:49:15 +00:00
|
|
|
broadcaster relay.Broadcaster
|
2023-10-20 19:56:18 +00:00
|
|
|
sub *relay.Subscription
|
2022-12-10 16:21:22 +00:00
|
|
|
cancel context.CancelFunc
|
2022-07-24 20:51:42 +00:00
|
|
|
adder Adder
|
|
|
|
}
|
|
|
|
|
2023-05-05 09:49:15 +00:00
|
|
|
func newRunnerService(broadcaster relay.Broadcaster, adder Adder) *runnerService {
|
2022-07-24 20:51:42 +00:00
|
|
|
return &runnerService{
|
|
|
|
broadcaster: broadcaster,
|
|
|
|
adder: adder,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-10 16:21:22 +00:00
|
|
|
func (r *runnerService) Start(ctx context.Context) {
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
r.cancel = cancel
|
2023-10-20 19:56:18 +00:00
|
|
|
r.sub = r.broadcaster.RegisterForAll(relay.WithBufferSize(relay.DefaultRelaySubscriptionBufferSize))
|
2022-07-24 20:51:42 +00:00
|
|
|
for {
|
|
|
|
select {
|
2022-12-10 16:21:22 +00:00
|
|
|
case <-ctx.Done():
|
2022-07-24 20:51:42 +00:00
|
|
|
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)
|
|
|
|
}
|
2022-07-24 20:51:42 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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()
|
2022-12-10 16:21:22 +00:00
|
|
|
r.cancel()
|
2022-07-24 20:51:42 +00:00
|
|
|
}
|