-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmux.go
274 lines (232 loc) · 6.6 KB
/
mux.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package dew
import (
"context"
"reflect"
"sync"
)
var (
_ Bus = (*mux)(nil)
)
// mux is the main struct where all handlers and middlewares are registered.
type mux struct {
parent *mux
inline bool
lock sync.RWMutex
entries *sync.Map
handler [ALL]Middleware
middlewares [mAll][]middleware
mHandlers [mAll]func(ctx Context, fn mHandlerFunc) error
cache *syncMap
// context pool
pool *sync.Pool
}
// New creates an instance of the Command Bus.
func New() Bus {
return newMux()
}
// OpType represents the type of operation.
type OpType uint8
const (
// ACTION indicates a command that modifies state.
ACTION OpType = 1 << iota
// QUERY indicates a command that fetches data.
QUERY
)
const ALL OpType = ACTION | QUERY
type mHandlerFunc func(ctx Context) error
type middlewareType int
const (
mCmd middlewareType = iota
mDispatch
mQuery
mAll
)
// newMux returns a newly initialized Mux object that implements the dispatcher interface.
func newMux() *mux {
mux := &mux{entries: &sync.Map{}, pool: &sync.Pool{}}
mux.pool.New = func() interface{} {
return &BusContext{}
}
mux.cache = &syncMap{kv: make(map[reflect.Type]any)}
return mux
}
// Use appends the middlewares to the mux middleware chain.
// The middleware chain will be executed in the order they were added.
func (mx *mux) Use(op OpType, middlewares ...func(next Middleware) Middleware) {
for _, mw := range middlewares {
mx.middlewares[mCmd] = append(mx.middlewares[mCmd], middleware{op: op, fn: mw})
}
}
// UseDispatch appends the middlewares to the dispatch middleware chain.
func (mx *mux) UseDispatch(middlewares ...func(next Middleware) Middleware) {
mx.addMiddleware(mDispatch, middlewares)
}
// UseQuery appends the middlewares to the query middleware chain.
func (mx *mux) UseQuery(middlewares ...func(next Middleware) Middleware) {
mx.addMiddleware(mQuery, middlewares)
}
func (mx *mux) addMiddleware(m middlewareType, mws []func(next Middleware) Middleware) {
for _, mw := range mws {
mx.middlewares[m] = append(mx.middlewares[m], middleware{fn: mw})
}
}
// Group creates a new mux with a copy of the parent middlewares.
func (mx *mux) Group(fn func(mx Bus)) Bus {
child := mx.child()
if fn != nil {
fn(child)
}
return child
}
// with creates a new mux with the given middlewares.
func (mx *mux) child() Bus {
// copy the parent middlewares
var mws [mAll][]middleware
for i := range mws {
mws[i] = make([]middleware, len(mx.middlewares[i]))
copy(mws[i], mx.middlewares[i])
}
return &mux{
parent: mx,
inline: true,
middlewares: mws,
entries: mx.entries,
cache: mx.cache,
}
}
// dispatch dispatches the command to the appropriate Executor.
func (mx *mux) dispatch(op OpType, ctx Context, h internalHandler) error {
hh := mx.handlerFor(op)
if hh == nil {
mx.updateRouteHandler(op)
hh = mx.handlerFor(op)
}
ctx.(*BusContext).handler = h
return hh.Handle(ctx)
}
func (mx *mux) handlerFor(op OpType) Middleware {
mx.lock.RLock()
defer mx.lock.RUnlock()
return mx.handler[op]
}
func (mx *mux) newDispatchHandler(m middlewareType, fn func(ctx Context) error) Middleware {
return exec(mx.middlewares[m], MiddlewareFunc(
func(ctx Context) error {
return fn(ctx)
}))
}
func (mx *mux) updateRouteHandler(op OpType) {
mx.lock.Lock()
defer mx.lock.Unlock()
mx.handler[op] = chain(op, mx.middlewares[mCmd], MiddlewareFunc(
func(ctx Context) error {
return ctx.(*BusContext).handler.Handle(ctx)
}))
}
func (mx *mux) updateHandler(m middlewareType) {
mx.lock.Lock()
defer mx.lock.Unlock()
mx.mHandlers[m] = func(ctx Context, fn mHandlerFunc) error {
return mx.newDispatchHandler(m, func(ctx Context) error {
return fn(ctx)
}).Handle(ctx)
}
}
// Register adds the handler to the mux for the given command type.
func (mx *mux) Register(handler interface{}) {
val := reflect.ValueOf(handler)
typ := val.Type()
// Convert to pointer if not already
if typ.Kind() != reflect.Ptr {
val = reflect.New(typ)
val.Elem().Set(reflect.ValueOf(handler))
typ = val.Type()
}
for i := 0; i < typ.NumMethod(); i++ {
method := typ.Method(i)
if isHandlerMethod(method) {
cmdType := method.Type.In(2).Elem()
if cmdType.Implements(reflect.TypeOf((*Action)(nil)).Elem()) ||
cmdType.Implements(reflect.TypeOf((*QueryAction)(nil)).Elem()) {
mx.addHandler(cmdType, val.Method(i).Interface())
}
}
}
mx.setupHandler()
}
func (mx *mux) setupHandler() {
if mx.mHandlers[mQuery] == nil {
mx.updateHandler(mQuery)
}
if mx.mHandlers[mDispatch] == nil {
mx.updateHandler(mDispatch)
}
if mx.parent != nil {
mx.parent.setupHandler()
}
}
func (mx *mux) addHandler(t reflect.Type, h any) {
mx.entries.Store(t, &handler{handler: h, mux: mx})
}
// isHandlerMethod checks if the method is a Executor method.
// A Executor method is a method that has 3 input parameters,
// the first is the receiver, the second is a context.Context,
// and the third is a pointer to a struct that implements the Action or QueryAction interface.
// Example:
//
// func (uh *UserHandler) Update(ctx context.Context, action *action.UpdateUser) error
func isHandlerMethod(m reflect.Method) bool {
return m.Type.NumIn() == 3 && isContextType(m.Type.In(1)) && m.Type.NumOut() == 1 && isErrorType(m.Type.Out(0))
}
var (
ctxType = reflect.TypeOf((*context.Context)(nil)).Elem()
errType = reflect.TypeOf((*error)(nil)).Elem()
)
func isContextType(t reflect.Type) bool {
return t == ctxType
}
func isErrorType(t reflect.Type) bool {
return t == errType
}
// exec constructs a middleware chain that executes in sequence and only once per context.
func exec(middlewares []middleware, command Middleware) Middleware {
if len(middlewares) == 0 {
return command
}
return func() Middleware {
return MiddlewareFunc(func(ctx Context) error {
idx := ctx.(*BusContext).mwsIdx
if idx < len(middlewares) {
ctx.(*BusContext).mwsIdx++
return middlewares[idx].fn(exec(middlewares, command)).Handle(ctx)
}
return command.Handle(ctx)
})
}()
}
func chain(op OpType, middlewares []middleware, command Middleware) Middleware {
// Wrap the end handler with the middleware chain
mws := filterMiddleware(op, middlewares)
if len(mws) == 0 {
return command
}
h := mws[len(mws)-1].fn(command)
for i := len(mws) - 2; i >= 0; i-- {
h = mws[i].fn(h)
}
return h
}
// filterMiddleware returns the middlewares that match the given operation type.
func filterMiddleware(op OpType, middlewares []middleware) []middleware {
var mws []middleware
for _, mw := range middlewares {
if mw.op&op != 0 {
mws = append(mws, mw)
}
}
return mws
}
type middleware struct {
op OpType
fn func(next Middleware) Middleware
}