github.com/MontFerret/ferret@v0.18.0/pkg/drivers/cdp/events/stream.go (about)

     1  package events
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/mafredri/cdp/rpcc"
     7  
     8  	"github.com/MontFerret/ferret/pkg/runtime/core"
     9  	"github.com/MontFerret/ferret/pkg/runtime/events"
    10  	"github.com/MontFerret/ferret/pkg/runtime/values"
    11  )
    12  
    13  type (
    14  	Decoder func(ctx context.Context, stream rpcc.Stream) (core.Value, error)
    15  
    16  	Factory func(ctx context.Context) (rpcc.Stream, error)
    17  
    18  	EventStream struct {
    19  		stream  rpcc.Stream
    20  		decoder Decoder
    21  	}
    22  )
    23  
    24  func NewEventStream(stream rpcc.Stream, decoder Decoder) events.Stream {
    25  	return &EventStream{stream, decoder}
    26  }
    27  
    28  func (e *EventStream) Close(_ context.Context) error {
    29  	return e.stream.Close()
    30  }
    31  
    32  func (e *EventStream) Read(ctx context.Context) <-chan events.Message {
    33  	ch := make(chan events.Message)
    34  
    35  	go func() {
    36  		defer close(ch)
    37  
    38  		for {
    39  			select {
    40  			case <-ctx.Done():
    41  				return
    42  			case <-e.stream.Ready():
    43  				val, err := e.decoder(ctx, e.stream)
    44  
    45  				if err != nil {
    46  					ch <- events.WithErr(err)
    47  
    48  					return
    49  				}
    50  
    51  				if val != nil && val != values.None {
    52  					ch <- events.WithValue(val)
    53  				}
    54  			}
    55  		}
    56  	}()
    57  
    58  	return ch
    59  }