github.com/MontFerret/ferret@v0.18.0/pkg/drivers/cdp/events/source.go (about) 1 package events 2 3 import ( 4 "context" 5 6 "github.com/mafredri/cdp/rpcc" 7 ) 8 9 type ( 10 // ID represents a unique event ID 11 ID int 12 13 // Event represents a system event that is returned from an event source 14 Event struct { 15 ID ID 16 Data interface{} 17 } 18 19 // Source represents a custom source of system events 20 Source interface { 21 rpcc.Stream 22 Recv() (Event, error) 23 } 24 25 // SourceFactory represents a function that creates a new instance of Source. 26 SourceFactory func(ctx context.Context) (Source, error) 27 28 StreamFactory func(ctx context.Context) (rpcc.Stream, error) 29 30 StreamDecoder func(stream rpcc.Stream) (interface{}, error) 31 32 // StreamSource represents a helper struct for generating custom event sources 33 StreamSource struct { 34 eventID ID 35 stream rpcc.Stream 36 decoder StreamDecoder 37 } 38 ) 39 40 var ( 41 Error = New("error") 42 ) 43 44 // NewStreamSource create a new custom event source based on rpcc.Stream 45 // eventID - is a unique event ID 46 // stream - is a custom event stream 47 // decoder - is a value conversion function 48 func NewStreamSource( 49 eventID ID, 50 stream rpcc.Stream, 51 decoder StreamDecoder, 52 ) Source { 53 return &StreamSource{eventID, stream, decoder} 54 } 55 56 func (src *StreamSource) ID() ID { 57 return src.eventID 58 } 59 60 func (src *StreamSource) Ready() <-chan struct{} { 61 return src.stream.Ready() 62 } 63 64 func (src *StreamSource) RecvMsg(m interface{}) error { 65 return src.stream.RecvMsg(m) 66 } 67 68 func (src *StreamSource) Close() error { 69 return src.stream.Close() 70 } 71 72 func (src *StreamSource) Recv() (Event, error) { 73 data, err := src.decoder(src.stream) 74 75 if err != nil { 76 return Event{}, err 77 } 78 79 return Event{ 80 ID: src.eventID, 81 Data: data, 82 }, nil 83 } 84 85 func NewStreamSourceFactory(eventID ID, factory StreamFactory, receiver StreamDecoder) SourceFactory { 86 return func(ctx context.Context) (Source, error) { 87 stream, err := factory(ctx) 88 89 if err != nil { 90 return nil, err 91 } 92 93 return NewStreamSource(eventID, stream, receiver), nil 94 } 95 }