2022-07-24 16:51:42 -04:00
|
|
|
package rest
|
|
|
|
|
|
|
|
import (
|
2022-12-10 12:21:22 -04:00
|
|
|
"context"
|
|
|
|
|
2022-11-09 15:53:01 -04:00
|
|
|
"github.com/waku-org/go-waku/waku/v2/protocol"
|
2023-05-05 15:19:15 +05:30
|
|
|
"github.com/waku-org/go-waku/waku/v2/protocol/relay"
|
2022-07-24 16:51:42 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type Adder func(msg *protocol.Envelope)
|
|
|
|
|
|
|
|
type runnerService struct {
|
2023-05-05 15:19:15 +05:30
|
|
|
broadcaster relay.Broadcaster
|
2023-10-21 01:26:18 +05:30
|
|
|
sub *relay.Subscription
|
2022-12-10 12:21:22 -04:00
|
|
|
cancel context.CancelFunc
|
2022-07-24 16:51:42 -04:00
|
|
|
adder Adder
|
|
|
|
}
|
|
|
|
|
2023-05-05 15:19:15 +05:30
|
|
|
func newRunnerService(broadcaster relay.Broadcaster, adder Adder) *runnerService {
|
2022-07-24 16:51:42 -04:00
|
|
|
return &runnerService{
|
|
|
|
broadcaster: broadcaster,
|
|
|
|
adder: adder,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-10 12:21:22 -04:00
|
|
|
func (r *runnerService) Start(ctx context.Context) {
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
r.cancel = cancel
|
2023-10-21 01:26:18 +05:30
|
|
|
r.sub = r.broadcaster.RegisterForAll(relay.WithBufferSize(relay.DefaultRelaySubscriptionBufferSize))
|
2022-07-24 16:51:42 -04:00
|
|
|
for {
|
|
|
|
select {
|
2022-12-10 12:21:22 -04:00
|
|
|
case <-ctx.Done():
|
2022-07-24 16:51:42 -04:00
|
|
|
return
|
2023-05-05 15:19:15 +05:30
|
|
|
case envelope, ok := <-r.sub.Ch:
|
2023-05-05 17:33:44 +05:30
|
|
|
if ok {
|
2023-05-05 15:19:15 +05:30
|
|
|
r.adder(envelope)
|
|
|
|
}
|
2022-07-24 16:51:42 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *runnerService) Stop() {
|
2023-01-06 18:37:57 -04:00
|
|
|
if r.cancel == nil {
|
|
|
|
return
|
|
|
|
}
|
2023-05-05 15:19:15 +05:30
|
|
|
r.sub.Unsubscribe()
|
2022-12-10 12:21:22 -04:00
|
|
|
r.cancel()
|
2022-07-24 16:51:42 -04:00
|
|
|
}
|