forked from looplab/eventhorizon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
commandhandler.go
80 lines (65 loc) · 2.1 KB
/
commandhandler.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
75
76
77
78
79
80
// Copyright (c) 2014 - The Event Horizon authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bus
import (
"context"
"errors"
"sync"
eh "github.com/2908755265/eventhorizon"
)
var (
// ErrHandlerAlreadySet is when a handler is already registered for a command.
ErrHandlerAlreadySet = errors.New("handler is already set")
// ErrHandlerNotFound is when no handler can be found.
ErrHandlerNotFound = errors.New("no handlers for command")
)
// CommandHandler is a command handler that handles commands by routing to the
// registered CommandHandlers.
type CommandHandler struct {
handlers map[eh.CommandType]eh.CommandHandler
handlersMu sync.RWMutex
}
// NewCommandHandler creates a CommandHandler.
func NewCommandHandler() *CommandHandler {
return &CommandHandler{
handlers: make(map[eh.CommandType]eh.CommandHandler),
}
}
// HandleCommand handles a command with a handler capable of handling it.
func (h *CommandHandler) HandleCommand(ctx context.Context, cmd eh.Command) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if err := eh.CheckCommand(cmd); err != nil {
return err
}
h.handlersMu.RLock()
defer h.handlersMu.RUnlock()
if handler, ok := h.handlers[cmd.CommandType()]; ok {
return handler.HandleCommand(ctx, cmd)
}
return ErrHandlerNotFound
}
// SetHandler adds a handler for a specific command.
func (h *CommandHandler) SetHandler(handler eh.CommandHandler, cmdType eh.CommandType) error {
h.handlersMu.Lock()
defer h.handlersMu.Unlock()
if _, ok := h.handlers[cmdType]; ok {
return ErrHandlerAlreadySet
}
h.handlers[cmdType] = handler
return nil
}