| 1 |
package events |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
|
| 9 |
"github.com/mesos/mesos-go/api/v1/lib/executor" |
| 10 |
) |
| 11 |
|
| 12 |
type ( |
| 13 |
|
| 14 |
|
| 15 |
Handler interface { |
| 16 |
HandleEvent(context.Context, *executor.Event) error |
| 17 |
} |
| 18 |
|
| 19 |
|
| 20 |
HandlerFunc func(context.Context, *executor.Event) error |
| 21 |
|
| 22 |
|
| 23 |
Handlers map[executor.Event_Type]Handler |
| 24 |
|
| 25 |
|
| 26 |
HandlerFuncs map[executor.Event_Type]HandlerFunc |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
func (f HandlerFunc) HandleEvent(ctx context.Context, e *executor.Event) error { return f(ctx, e) } |
| 31 |
|
| 32 |
type noopHandler int |
| 33 |
|
| 34 |
func (noopHandler) HandleEvent(_ context.Context, _ *executor.Event) error { return nil } |
| 35 |
|
| 36 |
|
| 37 |
const NoopHandler = noopHandler(0) |
| 38 |
|
| 39 |
|
| 40 |
func (hs Handlers) HandleEvent(ctx context.Context, e *executor.Event) (err error) { |
| 41 |
if h := hs[e.GetType()]; h != nil { |
| 42 |
return h.HandleEvent(ctx, e) |
| 43 |
} |
| 44 |
return nil |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
func (hs HandlerFuncs) HandleEvent(ctx context.Context, e *executor.Event) (err error) { |
| 49 |
if h := hs[e.GetType()]; h != nil { |
| 50 |
return h.HandleEvent(ctx, e) |
| 51 |
} |
| 52 |
return nil |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
func (hs Handlers) Otherwise(f HandlerFunc) HandlerFunc { |
| 58 |
if f == nil { |
| 59 |
return hs.HandleEvent |
| 60 |
} |
| 61 |
return func(ctx context.Context, e *executor.Event) error { |
| 62 |
if h := hs[e.GetType()]; h != nil { |
| 63 |
return h.HandleEvent(ctx, e) |
| 64 |
} |
| 65 |
return f(ctx, e) |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
func (hs HandlerFuncs) Otherwise(f HandlerFunc) HandlerFunc { |
| 72 |
if f == nil { |
| 73 |
return hs.HandleEvent |
| 74 |
} |
| 75 |
return func(ctx context.Context, e *executor.Event) error { |
| 76 |
if h := hs[e.GetType()]; h != nil { |
| 77 |
return h.HandleEvent(ctx, e) |
| 78 |
} |
| 79 |
return f(ctx, e) |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
var ( |
| 84 |
_ = Handler(Handlers(nil)) |
| 85 |
_ = Handler(HandlerFunc(nil)) |
| 86 |
_ = Handler(HandlerFuncs(nil)) |
| 87 |
) |