-
Notifications
You must be signed in to change notification settings - Fork 19
/
worker.go
74 lines (63 loc) · 2.15 KB
/
worker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package cocaine12
// Worker performs IO operations between an application
// and cocaine-runtime, dispatches incoming messages
// This is an adapter to WorkerNG
type Worker struct {
impl *WorkerNG
handlers *EventHandlers
terminationHandler TerminationHandler
}
// NewWorker connects to the cocaine-runtime and create WorkerNG on top of this connection
func NewWorker() (*Worker, error) {
impl, err := NewWorkerNG()
if err != nil {
return nil, err
}
return &Worker{impl, NewEventHandlers(), nil}, nil
}
// Used in tests only
func newWorker(conn socketIO, id string, protoVersion int, debug bool) (*Worker, error) {
impl, err := newWorkerNG(conn, id, protoVersion, debug, new(NullTokenManager))
if err != nil {
return nil, err
}
return &Worker{impl, NewEventHandlers(), nil}, nil
}
// SetDebug enables debug mode of the Worker.
// It allows to print Stack of a paniced handler
func (w *Worker) SetDebug(debug bool) {
w.impl.SetDebug(debug)
}
// EnableStackSignal allows/disallows the worker to catch
// SIGUSR1 to print all goroutines stacks. It's enabled by default.
// This function must be called before Worker.Run to take effect.
func (w *Worker) EnableStackSignal(enable bool) {
w.impl.EnableStackSignal(enable)
}
// Token returns the most recently viewed version of the authorization token.
func (w *Worker) Token() Token {
return w.impl.Token()
}
// SetTerminationHandler allows to attach handler which will be called
// when SIGTERM arrives
func (w *Worker) SetTerminationHandler(handler TerminationHandler) {
w.terminationHandler = handler
}
// On binds the handler for a given event
func (w *Worker) On(event string, handler EventHandler) {
w.handlers.On(event, handler)
}
// SetFallbackHandler sets the handler to be a fallback handler
func (w *Worker) SetFallbackHandler(handler FallbackEventHandler) {
w.handlers.SetFallbackHandler(RequestHandler(handler))
}
func (w *Worker) Run(handlers map[string]EventHandler) error {
for event, handler := range handlers {
w.On(event, handler)
}
return w.impl.Run(w.handlers.Call, w.terminationHandler)
}
// Stop makes the Worker stop handling requests
func (w *Worker) Stop() {
w.impl.Stop()
}