github.com/MontFerret/ferret@v0.18.0/pkg/drivers/cdp/events/wait.go (about) 1 package events 2 3 import ( 4 "context" 5 "time" 6 7 "github.com/MontFerret/ferret/pkg/drivers/cdp/eval" 8 "github.com/MontFerret/ferret/pkg/runtime/core" 9 "github.com/MontFerret/ferret/pkg/runtime/values" 10 ) 11 12 type ( 13 Function func(ctx context.Context) (core.Value, error) 14 15 WaitTask struct { 16 fun Function 17 polling time.Duration 18 } 19 ) 20 21 const DefaultPolling = time.Millisecond * time.Duration(200) 22 23 func NewWaitTask( 24 fun Function, 25 polling time.Duration, 26 ) *WaitTask { 27 return &WaitTask{ 28 fun, 29 polling, 30 } 31 } 32 33 func (task *WaitTask) Run(ctx context.Context) (core.Value, error) { 34 for { 35 if ctx.Err() != nil { 36 return values.None, ctx.Err() 37 } 38 39 out, err := task.fun(ctx) 40 41 // expression failed 42 // terminating 43 if err != nil { 44 return values.None, err 45 } 46 47 // output is not empty 48 // terminating 49 if out != values.None { 50 return out, nil 51 } 52 53 // Nothing yet, let's wait before the next try 54 <-time.After(task.polling) 55 } 56 } 57 58 func NewEvalWaitTask( 59 ec *eval.Runtime, 60 fn *eval.Function, 61 polling time.Duration, 62 ) *WaitTask { 63 return NewWaitTask( 64 func(ctx context.Context) (core.Value, error) { 65 return ec.EvalValue(ctx, fn) 66 }, 67 polling, 68 ) 69 }